Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Grep Alternatives to Return One Item

I'm looking at some jQuery code I'm writing at the moment and it just looks plain weird to my C# brain. Is there a better way of doing this?

var idToLookFor = 2;
var myArray = [{id:1},{id:2},{id:3}]

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

var itemFound = arrayItem[0];

I can understand grep returning an array as rather than it being a find type function its a filter type function so I guess the question should really be is there a function that will only return one item rather than an array?

like image 839
Jammer Avatar asked Aug 02 '13 13:08

Jammer


1 Answers

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
    }
}
like image 200
lewis Avatar answered Oct 14 '22 15:10

lewis