KJ3
KJ3

Reputation: 5298

JavaScript Most Efficient Way to find Object in Array

I can't seem to find an agreed-upon way to find an object in an array of objects by a single field, specifically a large string field such as a Mongo id. For example I have the following array:

[
    {
        _id: "55e4a11251e4c7914426xxxx,
        name: 'John'    
    }, {
        _id: "55e4a11251e4c7914426yyyy",
        name: 'Jack
    }
]

I now want to create a function to return the object from the array where the _id is equal. I have the following, but it seems like it could be improved upon:

function getObject(searchedId, array) {
    for (var i = 0; i < array.length; i++) {
        if (array[i]._id === searchedId) {
            return array[i];
        }
    }
}

Upvotes: 4

Views: 1017

Answers (3)

Legends
Legends

Reputation: 22692

This easiest way is by using the find method

var foundObj =  yourObjectArray.find((obj) => { return obj._id == id });

Instead of the lambda expression, you can also use a callback function.

Upvotes: 0

dlght
dlght

Reputation: 926

You can use filter:

function search(searchedId, array){
    var obj = array.filter(function ( obj ) {
        return obj._id === searchedId;
    })[0];
}

Note: .filter() is not implemented in IE8, but you easily deal with that using ES5-shim.

Upvotes: 1

Jon Trauntvein
Jon Trauntvein

Reputation: 4554

What you have is a linear search and it is probably the best that can be done unless the array is ordered in some way. If the array is ordered by the _id field, you can perform a binary search on the array which changes the lookup from an O(n) operation to O(log(n)).

Upvotes: 3

Related Questions