Quickest way of finding unique objects in a javascript array -
i have array of 15,000 javascript objects. each object has 2 fields:
{ name : "foo", address : "bar@moo.com" } i want create new array stores unique email addresses , corresponding names. far have method:
// temp1 array of 15,000 objects var arr = []; (var = 0; i<temp1.length; i++){ var count = 0; if(!arr.length){arr.push(temp1[i])}; for(var x = 0; x<arr.length; x++){ if(temp1[i].address === arr[x].address){ count++; if(temp1[i].name.length && !arr[x].name.length){arr[x] = temp1[i];} // choose new object if old 1 has no name field } if((x === arr.length -1) && count === 0){ arr.push(temp1[i]) } } } i have added requirement in here - if object in arr has blank string name field, , temp1 object does, want store temp1 object instead.
my current method takes 30s run in chrome , not ideal.
edit: clarify, i'm asking whether there more efficient method in javascript find unique objects in array. 1 method above create new array, iterate against original , each 1 loop through in new array check duplicates. i'm wondering what's out that more efficient this.
here's possibility
var tmp = {}; temp1.foreach(function(item) { var key = item.address; add = tmp[key] = tmp[key] || item; add.name = add.name || item.name; }); var addr = object.keys(tmp).map(function(t) { return tmp[t] }); caveat: ie9 or later - or use following polyfills lesser ie browsers
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/map map
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/foreach foreach
https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/object/keys object.keys
after taking consideration comments @dev-null
var tmp = {}, item, key, add, i, l = temp1.length, addr; for(i = 0; < l; i++) { item = temp1[i]; key = item.address; add = tmp[key] = tmp[key] || item; add.name = add.name || item.name; }; addr = new array(object.keys(tmp).length); = 0; for(key in tmp) { addr[i++] = tmp[key]; } that's on average twice fast first test (in firefox though)
and 64 times faster op's original script
edit: fastest though (in firefox)
var tmp = {}, item, key, add, i, l = temp1.length, addr; for(i = 0; < l; i++) { item = temp1[i]; key = item.address; add = tmp[key] = tmp[key] || item; add.name = add.name || item.name; }; addr = object.keys(tmp).map(function(t) { return tmp[t] });
Comments
Post a Comment