cresjoy cresjoy - 4 months ago 15
Javascript Question

Understanding finding object in an array

My Attempt

Hi, so we can do something like

var myArray = [{'id':'73','foo':'bar'},{'id':'45','foo':'ye'}];
function getById(id, myArray) {
return myArray.filter(function(obj) {
if(obj.id == id) {
return obj
}
})
}

get_my_obj = getById(45, myArray);
console.log(get_my_obj);


To filter our object. However after some testing I realized that I wasn't getting the result I needed, I noticed that if I add
[0]
as such

return myArray.filter(function(obj) {
if(obj.id == id) {
return obj
}
})[0]


Problem

This works perfectly. Why do I need
[0]
?

Answer

Array.prototype.filter filters an array; it removes the elements from the array which don't fit your predicate. The result is an array, presumably shorter than the one you started with.

What you're looking for is Array.prototype.find, which returns the first match only.

Comments