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!
Top comments (3)
man, you don't know how you helped me!
thank you so much, keep it up,
you improved mine with this post here
I'm really help to help you, Samuel! I'll try to write more often. Thank you! =)
Can you elaborate more about this?