Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Compare two Arrays with Objects and create new array with unmatched objects

I have the following two Javascript arrays:

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

I now want a new array array3 that contains only the objects that aren't already in array2, so:

const array3 = [{ id: 2}, { id: 4 }];

I have tried the following but it returns all objects, and when I changed the condition to === it returns the objects of array2.

const array3 = array1.filter(entry1 => {
  return array2.some(entry2 => entry1.id !== entry2.id);
});

Any idea? ES6 welcome

like image 745
mxmtsk Avatar asked Dec 04 '17 22:12

mxmtsk


People also ask

How do you compare two arrays to find matches?

JavaScript finding non-matching values in two arrays The code will look like this. const array1 = [1, 2, 3, 4, 5, 6]; const array2 = [1, 2, 3, 4, 5, 6, 7, 8, 9]; const output = array2. filter(function (obj) { return array1. indexOf(obj) === -1; }); console.

How do I compare two arrays of objects in Lodash?

In Lodash, we can deeply compare two objects using the _. isEqual() method. This method will compare both values to determine if they are equivalent.


1 Answers

You could reverse the comparison (equal instead of unqual) and return the negated result of some.

const
    array1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }],
    array2 = [{ id: 1 }, { id: 3 }],
    array3 = array1.filter(entry1 => !array2.some(entry2 => entry1.id === entry2.id));
    //                               ^                                ^^^

console.log(array3);
like image 95
Nina Scholz Avatar answered Oct 27 '22 00:10

Nina Scholz