Yewon Kim
Yewon Kim

Reputation: 53

Basic Javascript map, filter question in array

I want to get things with collectionId that match those in the list. In other words, I want to get the desired result. How can I do it?? please help me....

const music_list = {
  "resultCount": 50,
  "results": [{
      "collectionId": 123,
      "ArtistId": "BLACKPINK"
    },
    {
      "collectionId": 456,
      "ArtistId": "BTS"
    },
    {
      "collectionId": 789,
      "ArtistId": "CARDIBI"
    }
  ]
}
const list = [123, 142, 118];

In this situation, Desired result = [{"collectionId":123, "ArtistId": "BLACKPINK"}]

Upvotes: 0

Views: 50

Answers (1)

CherryDT
CherryDT

Reputation: 29012

You can map the list to the relevant objects - for each ID, you will try to find the corresponding object in the results array. At the end, you can filter out the missing elements.

const result = list
  .map(id => music_list.results.find(item => item.collectionId === id))
  .filter(item => item)

How it works: music_list.results.find(item => item.collectionId === 123) would return the item in music_list.results that has collectionId: 123 (or undefined if no such item exists). Furthermore, list.map(id => ...something...) would apply the ...something... to each id in the list and return a new array with the results. So here we map the IDs to the matching objects in your results array. At the end, we use filter to remove elements that are falsy (undefined is falsy), i.e. remove the missing elements from the result (without that, it would return something like [{ ... }, undefined, undefined]).

You can see it in action here:

const music_list = {
  "resultCount": 50,
  "results": [
    {
      "collectionId": 123,
      "ArtistId": "BLACKPINK"
    },
    {
      "collectionId": 456,
      "ArtistId": "BTS"
    },
    {
    "collectionId": 789,
    "ArtistId": "CARDIBI"
    }
  ]
}

const list = [123, 142, 118];

const result = list
  .map(id => music_list.results.find(item => item.collectionId === id))
  .filter(item => item);

console.log(result);

Upvotes: 2

Related Questions