0

I have an array: var a = ['h1', 'h2', 'h3']

and array of objects: var b = [{name: 'h1', id: 3}, {name: 'h2', id: 4}, {name: 'h3', id: 5}]

How do I find common part and extract id's only as a new array:

[3, 4, 5]

with pure javascript?

pitmod
  • 63
  • 5
  • Does this answer your question? [Simplest code for array intersection in javascript](https://stackoverflow.com/questions/1885557/simplest-code-for-array-intersection-in-javascript) – Natixco Feb 19 '20 at 17:20
  • Filter will return a new array and then you can simply take out the ids from it. – Natixco Feb 19 '20 at 17:21

2 Answers2

1

This should output the values to c.

let c = [];
b.forEach(obj => {
   const i = a.indexOf(obj.name);
    c[i] = obj.id;
})
Gene Sy
  • 1,325
  • 2
  • 10
  • 17
1

If you need check names with the 'a' array.

let a = ['h1', 'h2', 'h3']
let b = [{name: 'h1', id: 3}, {name: 'h2', id: 4}, {name: 'h3', id: 5}]
let result = []

b.forEach(item => {
  if (a.indexOf(item.name) >= 0) {
      result = [
          ...result,
          item.id
      ]
   }
})