4

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];
        }
    }
}
1
  • 3
    "but it seems like it could be improved upon". Why do you think so? Commented Oct 6, 2015 at 21:40

3 Answers 3

3

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

Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.