JavaScript The most efficient way to find an object in an array

I cannot find a consistent way to search for an object in an array of objects with a single field, in particular a large string field such as the Mongo identifier. For example, I have the following array:

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

Now I want to create a function to return an object from an array, where _id is equal. I have the following, but it looks like it can be improved:

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

You have a linear search, and probably this is the best thing to do if the array is not sorted in some way. If the array is ordered by the _id field, you can perform a binary search in the array, which changes the search from O (n) to O (log (n)).

+2
source

:

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

..filter() IE8, ES5-shim.

+1

- find

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

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

0
source

Source: https://habr.com/ru/post/1610506/