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;
    });
}
Share:
13,002

Related videos on Youtube

Luis Rizo
Author by

Luis Rizo

In love with app development.

Updated on June 04, 2022

Comments

  • Luis Rizo
    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
    dodov about 7 years
    You talk about Array#every, but use some() shortly after. Is it a typo, or I misunderstood something?
  • Nina Scholz
    Nina Scholz about 7 years
    i mean Array#some, of course.
  • Manjeet Singh
    Manjeet Singh about 7 years
    you can even use filter for keeping only the desired elements of array
  • Nina Scholz
    Nina Scholz about 7 years
    @ManjeetSingh, filter returns an array as well, but op does not wand an array.
  • Manjeet Singh
    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
    Nina Scholz about 7 years
    @ManjeetSingh, then you have to iterate all objects.