Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better way to find object in array instead of looping?

Example

Link: http://jsfiddle.net/ewBGt/

var test = [{
    "name": "John Doo"
}, {
    "name": "Foo Bar"
}]

var find = 'John Doo'

console.log(test.indexOf(find)) // output: -1
console.log(test[find]) // output: undefined

$.each(test, function(index, object) {
    if(test[index].name === find)
        console.log(test[index]) // problem: this way is slow
})

Problem

In the above example I have an array with objects. I need to find the object that has name = 'John Doo'

My .each loop is working, but this part will be executed 100 times and test will contain lot more objects. So I think this way will be slow.

The indexOf() won't work because I cannot search for the name in object.

Question

How can I search for the object with name = 'John Doo' in my current array?

like image 739
Ron van der Heijden Avatar asked Apr 02 '13 14:04

Ron van der Heijden


3 Answers

jQuery $.grep (or other filtering function) is not the optimal solution.

The $.grep function will loop through all the elements of the array, even if the searched object has been already found during the loop.

From jQuery grep documentation :

The $.grep() method removes items from an array as necessary so that all remaining items pass a provided test. The test is a function that is passed an array item and the index of the item within the array. Only if the test returns true will the item be in the result array.

Provided that your array is not sorted, nothing can beat this:

var getObjectByName = function(name, array) {

    // (!) Cache the array length in a variable
    for (var i = 0, len = test.length; i < len; i++) {

        if (test[i].name === name)
            return test[i]; // Return as soon as the object is found

    }

    return null; // The searched object was not found

}
like image 66
Luca Fagioli Avatar answered Oct 13 '22 23:10

Luca Fagioli


I have done sometimes "searchable map-object" in this kind of situation. If the array itself is static, you can transform in to a map, where array values can be keys and map values indexes. I assume values to be unique as in your example.

Lo-Dash (www.lodash.com) has create selection of utils for easily looping etc. Check it out!

Note: But often you really don't have to worry about looping trough array with 100 elements.

like image 39
Matti Simperi Avatar answered Oct 14 '22 01:10

Matti Simperi


If you just want to find out if the value is there, you can use lodash's includes function like this:

var find = 'John Doo'

[{ "name": "John Doo" }, { "name": "Foo Bar" }].some(function (hash) {
    if (_.includes(hash, find)) return true;
});

Documentation:

  • _.includes()
  • Array.prototype.some()
like image 3
tomekwi Avatar answered Oct 14 '22 01:10

tomekwi