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?
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With