javascript - which approach is best to search object in array? -
i've sorted following ways search object in array. question has been asked countless times want know of best following ways. if there's i'd know too.
using $.grep()
function is_in_array(arr,element){ var result = $.grep(arr, function(e){ return e.id == element; }); return result.length; }
above function returns length of array.
- 0 when element not present
- 1 when element present
- length > 1 if more elements same value present
using lookup object
var lookup = {}; (var = 0, len = array.length; < len; i++) { lookup[array[i].id] = array[i]; }
this way don't need traverse entire array each time. i'd check lookup[id]
instead.
for loop in traditional way
function in_array(array, id) { for(var i=0;i<array.length;i++) { if(array[i].id === id) { return true; } } return false; }
to check if element exists, i'd call in_array(arr,element)
.
which approach best ? question sounds duplicate , want make sure best these 3 only.
update
array contain objects --
var arr = []; var nameobj = {}; nameobj.label = "somename"; nameobj.id = 123; arr.push(nameobj); . . .
you use combination of json
(for comparison) , array.filter
method:
var findvalue = json.stringify([somevalue]), ,found = [array].filter( function(a){return json.stringify(a) === findvalue;}).length ; // found > 0 means: findvalue found
a jsfiddle example
more array.filter
, shim older browsers @mdn
Comments
Post a Comment