Skip to content

Instantly share code, notes, and snippets.

@alexleone
Created April 17, 2020 18:33
Show Gist options
  • Save alexleone/5c05cee21a50e5993a66f3ce0806b5ce to your computer and use it in GitHub Desktop.
Save alexleone/5c05cee21a50e5993a66f3ce0806b5ce to your computer and use it in GitHub Desktop.
Difference between two arrays in javascript ES7.
// Intersection
let intersection = arr1.filter(x => arr2.includes(x));
// For [1,2,3] [2,3] it will yield [2,3]. On the other hand, for [1,2,3] [2,3,5] will return the same thing.
// Difference
let difference = arr1.filter(x => !arr2.includes(x));
// For [1,2,3] [2,3] it will yield [1]. On the other hand, for [1,2,3] [2,3,5] will return the same thing.
// For a symmetric difference, you can do:
let difference = arr1
.filter(x => !arr2.includes(x))
.concat(arr2.filter(x => !arr1.includes(x)));
// This way, you will get an array containing all the elements of arr1 that are not in arr2 and vice-versa
// Usage as Array.prototype
Array.prototype.diff = function(arr2) { return this.filter(x => arr2.includes(x)); }
[1, 2, 3].diff([2, 3])
// Original Stack Overflow
// https://stackoverflow.com/questions/1187518/how-to-get-the-difference-between-two-arrays-in-javascript
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment