How to get the difference between two arrays
César O. Araújo
Posted on October 19, 2020
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]
and
const initialWithMoreNumbers = [1, 2, 4, 7, 9, 5, 3]
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)
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))
after return, our result will be:
console.log(result) //[4, 9]
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)))
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!
Posted on October 19, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.