简体   繁体   中英

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];
        }
    }
}

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)).

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM