-1

I have the following

const A = ['test 105', 'test 300']
 const B = [
      { name: 'test 105', id: 1 },
      { name: 'test 300', id: 2 },
      { name: 'test 3', id: 29 },
      { name: 'test 20', id: 20 }
           ]

I need to check if const B.name is equal to any of the values in const A and return only the matches from const B.

So I need the final return to be

 const B = [
      { name: 'test 105', id: 1 },
      { name: 'test 300', id: 2 }
           ]

I was able to do this with 1 element but I want to check against const A because it might have more values in the future

const filtered = parsedResponse.filter(element => element.name == 'test 105')
 console.log(filtered)

Any help is appreciated Thanks

AbdA
  • 790
  • 7
  • 16
  • 2
    `B.filter(k=>A.includes(k.name))` – gorak Jun 06 '20 at 16:29
  • 1
    This question has been answered about a thousand times. – zfrisch Jun 06 '20 at 16:32
  • @zfrisch I checked stackoverflow a thousands time I didn't find it maybe my search terms were wrong. I work with Python and R and this would have been easier in Python but for this I needed javascript and I am not as good in javascript – AbdA Jun 06 '20 at 16:37
  • 1
    @AbdullahAlbyati You already have `parsedResponse.filter(element => element.name == 'test 105')` working for one item. The next step is trivial by searching “test if value is in array”: [Check if an element is present in an array](https://stackoverflow.com/q/7378228/4642212). There are multiple small steps to this problem, and you were only missing a single tiny step which has been answered multiple times already. Why search for _all_ the steps at once? – Sebastian Simon Jun 06 '20 at 16:39
  • Closest question to yours: [filtering an array of objects based on another array in javascript](https://stackoverflow.com/questions/46894352/filtering-an-array-of-objects-based-on-another-array-in-javascript). – Sebastian Simon Jun 06 '20 at 16:44

1 Answers1

6

You can filter it out based on the presence of object in second array.

const A = ['test 105', 'test 300'];
const B = [ { name: 'test 105', id: 1 }, { name: 'test 300', id: 2 }, { name: 'test 3', id: 29 }, { name: 'test 20', id: 20 } ];

const result = B.filter(k=>A.includes(k.name));

console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19