How to get the difference between two arrays

oaraujocesar

César O. Araújo

Posted on October 19, 2020

How to get the difference between two arrays

Hey, everyone! how are you guys doing? :)

I recently passed through a situation where I needed to get the difference between two arrays.

Messing around with arrays is a kind of tricky sometimes so I decided to share a simple solution for this specific case.

Let's declare two simple arrays:

 const initialNumbers = [1, 2, 5, 7, 3]
Enter fullscreen mode Exit fullscreen mode

and

 const initialWithMoreNumbers = [1, 2, 4, 7, 9, 5, 3]
Enter fullscreen mode Exit fullscreen mode

Alright, now we must find the intersection between them.

Arrays have some great methods provided by ES6+ features like filter.

With Array.filter() we can loop through an array and make some logic for every item in the array.

let result = initialWithMoreNumbers.filter(number => number)
Enter fullscreen mode Exit fullscreen mode

the code above will return every item in a new array, but we can do more than this, right?

we can verify if an item of the first array is NOT included in the second one like this:

let result = initialWithMoreNumbers.filter(number => !initialNumbers.includes(number))
Enter fullscreen mode Exit fullscreen mode

after return, our result will be:

console.log(result) //[4, 9]
Enter fullscreen mode Exit fullscreen mode

And how about array of objects?

If you need to compare keys in objects inside arrays, you just need to add a new method called array.every() to loop again and search what you need:

const people = [{name: 'cesar', age: 23}]
const morePeople = [{name: 'cesar', age: 23}, {name: 'kevin', age: 26}, {name: 'pedro', age: 25}]

let result2 = morePeople.filter(person => people.every(person2 => !person2.name.includes(person.name)))
Enter fullscreen mode Exit fullscreen mode

array.every() will loop through an array and return each element that passed on the test provided. In this case, if the name of the person in the second array does not contains the name of the person in the first one.

You can try this out by yourself with the age field!

Hope it helps! see ya!

💖 💪 🙅 🚩
oaraujocesar
César O. Araújo

Posted on October 19, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related