-1

I have an array of object and one array with integer ids.

I want to only have those entries in array of object whose ids are matched with array with has those ids in react jsx.

Ex:

A = [(0)-> id:'123', name:'john', city:'Newyork']
        [(1)-> id:'345', name:'martin', city:'Tokyo']
        [(2)-> id:'456', name:'lee', city:'Malbonre']
        [(3)-> id:'567', name:'roman', city:'Delhi']
        [(4)-> id:'789', name:'julie', city:'US']

B = [123, 456,567]

I want the result in such a way that array A should have only

 A = [(0)-> id:'123', name:'john', city:'Newyork']
        [(1)-> id:'456', name:'lee', city:'Malbonre']
        [(2)-> id:'567', name:'roman', city:'Delhi']
sagar verma
  • 404
  • 4
  • 10
  • 1
    Are you sure you're using Javascript? The stabby lambda syntax is not native to JS. Do you mean `(0)=> id:'123', name:'john', city:'Newyork']`, etc? If so, why is an integer the function param? – Abe Nov 20 '22 at 07:21

2 Answers2

1

use filter with includes

const A = [{id:'123', name:'john', city:'Newyork'},
        { id:'345', name:'martin', city:'Tokyo'},
       {id:'456', name:'lee', city:'Malbonre'},
       { id:'567', name:'roman', city:'Delhi'},
       {id:'789', name:'julie', city:'US'}]

const B = [123, 456,567]

const result = A.filter(i => B.includes(Number(i.id)))

console.log(result)
Sachila Ranawaka
  • 39,756
  • 7
  • 56
  • 80
1
  const A = [
    { id: "123", name: "john", city: "Newyork" },
    { id: "345", name: "martin", city: "Tokyo" },
    { id: "456", name: "lee", city: "Malbonre" },
    { id: "567", name: "roman", city: "Delhi" },
    { id: "789", name: "julie", city: "US" }
  ];
  const B = [123, 456, 567];
  const result = A.filter((item, index) => B.includes(Number(item.id)));

https://codesandbox.io/s/new?file=/src/App.js:56-421

Kamran Davar
  • 427
  • 2
  • 12