Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
154
rated 0 times [  157] [ 3]  / answers: 1 / hits: 18668  / 11 Years ago, fri, august 2, 2013, 12:00:00

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?


More From » jquery

 Answers
21

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

[#76566] Thursday, August 1, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kennedysaraiw

Total Points: 552
Total Questions: 99
Total Answers: 109

Location: South Sudan
Member since Sun, Jul 11, 2021
3 Years ago
;