-5

Let's say we have:

var array1 = [{ id: 1 }, { id: 4}, { id: 3 }] 
var array2 = [{ id: 1 }, { id: 2}] 

I know you can concat the two arrays like this (without having duplicates):

Array.from(new Set(array1.concat(array2)))

Now, how to create a new array with only the objects that share the same values?

var array2 = [{ id: 1 }] 
alex
  • 7,111
  • 15
  • 50
  • 77

3 Answers3

2

You can use .filter() and .some() to extract matching elements:

let array1 = [{ id: 1 }, { id: 4}, { id: 3 }] 
let array2 = [{ id: 1 }, { id: 2}] 

let result = array1.filter(({id}) => array2.some(o => o.id === id));

console.log(result);

Useful Resources:

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

You could take a set with the id of the objects and filter array2

var array1 = [{ id: 1 }, { id: 4}, { id: 3 }] ,
    array2 = [{ id: 1 }, { id: 2}],
    s = new Set(array1.map(({ id }) => id)),
    common = array2.filter(({ id }) => s.has(id));
    
console.log(common);

The requested sameness with identical objects.

var array1 = [{ id: 1 }, { id: 4}, { id: 3 }] ,
    array2 = [array1[0], { id: 2}],
    s = new Set(array1),
    common = array2.filter(o => s.has(o));
    
console.log(common);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

Assuming, by your definition, that the objects, even if they have the same structure, are not really the same object, I define an 'equality function', and then, with filter and some:

var array1 = [{ id: 1 }, { id: 4}, { id: 3 }] 
var array2 = [{ id: 1 }, { id: 2}];

var equal = function(o1, o2) { return o1.id === o2.id };

var result = array2.filter(function(item1) {
  return array1.some(function(item2) { return equal(item1, item2) });
});

console.log(result);
Oscar Paz
  • 18,084
  • 3
  • 27
  • 42