How to return an object from an array in JavaScript
You need to use the index for the array.
people[i] // for the object people[i].isAstronaut // for a property of the object
Then you need only a check if isAstronaut
is true
and return with the item.
At the end outside of the for
loop, return null
, for a not found astronaut.
If you check inside the loop, you will return too early with the wrong result.
function findFirstAstronaut(people) {
for (let i = 0; i < people.length; i++) {
if (people[i].isAstronaut) {
return people[i];
}
}
return null;
}
ES6 introduces a new way to achieve this, if ES6 is an option for you:
myArray.find(item => {
return item.isAstronaut
})
Or even more abbreviated:
myArray.find(item => item.isAstronaut)
find()
is a one of the new iterators, along with filter()
and map()
and others for more easily working with arrays. find()
will return the first item in your array that matches the condition. The =>
or "arrow function" means that you do not need to explicitly include the return statement.
Read more about ES6 iterators.
One liner
arr.filter(item => item.isAstronaut)[0]