The original idea with the function below was that it should return the card (an object) only if the ID matched, however, it didn't return anything (it returned undefined):
showDetails(cards, id){
cards.map(function(card, index){
if(card.id==id){
console.log(card);
return card;
}
})
}
Then I realized that I had the scope of return wrong and that I needed to return what the loop returned, so I came up with this:
showDetails(cards, id){
return (cards.map(function(card, index){
if(card.id==id){
return card;
}
}))
}
The result of the code above is: [undefined, Object]
I just want this function showDetails to return the object, not an array.
Thank you!
You could use Array#some
with early exit.
function showDetails(cards, id) {
var result;
cards.some(function(card) {
if (card.id === id) {
result = card;
return true;
}
});
return result;
}
Or use an ES6 method Array#find
function showDetails(cards, id) {
return cards.find(function(card) {
return card.id === id;
});
}
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