0

I have an array

const dataitems =  [
    {name:'test1', id:1},
    {name:'test2', id:2},
    {name:'test3', id:3}
  ]

const compares = [1,3]

So i want only to get the values of dataitems which id's are contained in compares array values

so at the end i expect to have a final array as

const ffinaldataitems =  [
    {name:'test1', id:1},
    {name:'test3', id:3}
  ]

which excludes the id 2

So i have tried the following but am stuck

  let finaldataitems = []
  dataitems.forEach(item=>{
         if(item.id ) //stuck on how to check and push to the array
  })

How do i proceed

Geoff
  • 6,277
  • 23
  • 87
  • 197

3 Answers3

1

You can try with Array.prototype.filter()

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

And Array.prototype.includes()

The includes() method determines whether an array includes a certain value among its entries, returning true or false as appropriate.

const dataitems =  [
  {name:'test1', id:1},
  {name:'test2', id:2},
  {name:'test3', id:3}
];

const compares = [1,3];

let finaldataitems = dataitems.filter(item => compares.includes(item.id));

console.log(finaldataitems);
Mamun
  • 66,969
  • 9
  • 47
  • 59
0

You can convert compares to Set and then use filter() on dataitems and check is set contains the id of object using Set.prototype.has

Note: for simplicity you can do that without Set using includes() but it will change the Time-Complexity of algorithm from O(n) to O(n ^ 2)

const dataitems =  [
    {name:'test1', id:1},
    {name:'test2', id:2},
    {name:'test3', id:3}
  ]

const compares = [1,3];
let set = new Set(compares);
const res = dataitems.filter(x => set.has(x.id));
console.log(res)

Another way of doing that is making an object whose keys will id of items. And then use map() on compares to return the item from the previously made object.

const dataitems =  [
    {name:'test1', id:1},
    {name:'test2', id:2},
    {name:'test3', id:3}
  ]

const compares = [1,3];
let obj = dataitems.reduce((ac,a) => (ac[a.id] = a, ac), {});
let res = compares.map(x => obj[x]);
console.log(res)
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

While you're in the loop you could check if item.id exists in the compares array using indexOf:

const dataitems = [{
    name: 'test1',
    id: 1
  },
  {
    name: 'test2',
    id: 2
  },
  {
    name: 'test3',
    id: 3
  }
];

const compares = [1, 3];
let finaldataitems = []
dataitems.forEach(item => {
  if (compares.indexOf(item.id) > -1)
    finaldataitems.push(item);
});

console.log(finaldataitems);
shrys
  • 5,860
  • 2
  • 21
  • 36