Domanda

I've sorted following ways to search for an object in array. This question has been asked like countless times but I want to know which of the best from following ways. If there's another I'd like to know that 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 with same value present

using lookup object

var lookup = {};
for (var i = 0, len = array.length; i < len; i++) {
    lookup[array[i].id] = array[i];
}

This way I don't need to traverse entire array each time. I'd just check for 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 is best ? Question seriously sounds duplicate and it is but I just want to make sure which is best from these three only.

Update

Array will contain objects like --

var arr = [];
var nameObj = {};

nameObj.label = "somename";
nameObj.id = 123;
arr.push(nameObj);
.
.
.
È stato utile?

Soluzione

You could also use a combination of JSON (for comparison) and the 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 about Array.filter and a shim for older browsers @MDN

Altri suggerimenti

You could use the built-in map() method instead of a loop:

var lookup=array.map(function(e){return e.id;});

(Not supported in IE 8)

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top