1

I have 2 arrays and I want to filter one of the arrays with another array.

2 arrays designed like this

array1= [{id:23},{id:11},{id:435}]

array2= [23, 435, 5]

I want to check and get items only if id of objects inside array1 is equal to one of the ids (string values ) in array2

I found a simple solution like this

var filtered=[1,2,3,4].filter(function(e){return this.indexOf(e)<0;},[2,4]);

but my case is a bit different, I dont know how to make return part, how can I get indexes of each array ?

var filtered=array1.filter(function(e){return e.id === ??},array2);
Rasim Avcı
  • 1,123
  • 2
  • 10
  • 16

2 Answers2

1

You could just look up the index by using the id property.

var array1 = [{ id: 23 }, { id: 11 }, { id: 435 }],
    array2 = [23, 435, 5],
    filtered = array1.filter(function (o) {
        return array2.indexOf(o.id) > -1;
    });
    
console.log(filtered);

ES6

var array1 = [{ id: 23 }, { id: 11 }, { id: 435 }],
    array2 = [23, 435, 5],
    filtered = array1.filter(({ id }) => array2.includes(id));
    
console.log(filtered);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

You can use .filter and essentially check if the object id exists in array2. There are several ways to do that including .find and .findIndex. I would use .some which returns true if a single match is found.

array1.filter(obj => array2.some(id => id === obj.id));
Explosion Pills
  • 188,624
  • 52
  • 326
  • 405