Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a map function return a single value rather than an array?

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!

like image 855
Luis Rizo Avatar asked Feb 25 '17 22:02

Luis Rizo


1 Answers

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;
    });
}
like image 182
Nina Scholz Avatar answered Oct 15 '22 11:10

Nina Scholz