jQuery Grep Alternatives to Return One Item

This answer to another question points out that grep will continue looping over the array even after it has found the right answer. Not an issue in the above example but if your array could be much larger it's worth noting: non grep solution

It's just a for loop that is wrapped in a function that returns the object it finds. Even if you stick with the grep method I'd still abstract your logic into some reusable function and keep it in a nice helper file somewhere.

I'm posting a modified version of the answer purely so you can see what I mean before deciding if you want to follow the link:

for (var i = 0, len = myArray.length; i < len; i++) 
{
    if (myArray[i].id === idToLookFor)
    {
        return myArray[i]; // Return as soon as the object is found
    }
}

Well, if you like using jQuery generic function style, you could add something like this in your personal library:

$.extend( {
    findFirst: function( elems, validateCb ){
        var i;
        for( i=0 ; i < elems.length ; ++i ) {
            if( validateCb( elems[i], i ) )
                return elems[i];
        }
        return undefined;
    }
} );

Usage for your example:

var result = $.findFirst( myArray, function(elm) {
    return elm.id == idToLookFor;
});

Of course, you could instead use your own namespace...

I assume your concern is with code readability. I think using directly a language loop solution for this matter is also quite fine.

You could also be concerned with waste, as there is no need to maintain another array structure just for this, but at least for your example it seems like a micro-optimisation issue.


Expanding on Blazemonger's comment:

var itemFound = myArray[idToLookFor - 1]

should get you the item you're looking for if I understand your question correctly. Note the -1 to account for indexing from 1

EDIT: this also assumes that the array will always be sorted in ascending order by ID as it is in your question. If your id's do increment nicely but the array is not initially sorted by them see: Sort array of objects by string property value in JavaScript