0

Asking for improved solution

Hi, I have 2 arrays and I want to filter one with the only value presented in the other.

i.e.

data1 = [
    {
        "c_id": 90,
        "c_name": "Test 1",
    },
    {
        "c_id": 95,
        "c_name": "Test 2",
    },
    {
        "c_id": 93,
        "c_name": "Test 3",
    }
]

data2 = [
    {
        "id": 92,
        "name": "Test 4",
        "rates": []
    },
    {
        "id": 90,
        "name": "Test 1",
        "rates": []
    },
    {
        "id": 95,
        "name": "Test 2",
        "rates": []
    },
    {
        "id": 93,
        "name": "Test 3",
        "rates": []
    },
]

From the above array, I want to filter data2 with only the id presented in the data1.

I have the below code

let c = []
data1.filter(b => {
  if (data2.find(a => a.id == b.c_id)) {
    c.push(data2.find(a => a.id == b.c_id))
  }
})
console.log(c)

Which correctly. Please anyone can tell is there any improved solution for it?

Rich
  • 155
  • 1
  • 8
  • 23

1 Answers1

0

You can create a set of data1 ids and use Array.filter to filter out the id which is present in the set.

const data1 = [
  {
    c_id: 90,
    c_name: "Test 1",
  },
  {
    c_id: 95,
    c_name: "Test 2",
  },
  {
    c_id: 93,
    c_name: "Test 3",
  },
];

const data2 = [
  {
    id: 92,
    name: "Test 4",
    rates: [],
  },
  {
    id: 90,
    name: "Test 1",
    rates: [],
  },
  {
    id: 95,
    name: "Test 2",
    rates: [],
  },
  {
    id: 93,
    name: "Test 3",
    rates: [],
  },
];

const set = new Set(data1.map((item) => item.c_id));
const result = data2.filter((item) => set.has(item.id));
console.log(result);
Rahul Sharma
  • 9,534
  • 1
  • 15
  • 37