How do I make a map function return a single value rather than an array?
13,002
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;
});
}
Related videos on Youtube
Comments
-
Luis Rizo almost 2 years
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!
-
dodov about 7 yearsYou talk about
Array#every
, but usesome()
shortly after. Is it a typo, or I misunderstood something? -
Nina Scholz about 7 yearsi mean
Array#some
, of course. -
Manjeet Singh about 7 yearsyou can even use filter for keeping only the desired elements of array
-
Nina Scholz about 7 years@ManjeetSingh, filter returns an array as well, but op does not wand an array.
-
Manjeet Singh about 7 years@NinaScholz, yeah you are right but if filter is returning an array with single element we can easily convert that to object by array[0],
-
Nina Scholz about 7 years@ManjeetSingh, then you have to iterate all objects.