Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the difference between two arrays in JavaScript?

Is there a way to return the difference between two arrays in JavaScript?

For example:

var a1 = ['a', 'b']; var a2 = ['a', 'b', 'c', 'd'];  // need ["c", "d"] 
like image 625
John Adawan Avatar asked Jul 27 '09 10:07

John Adawan


People also ask

Can we compare two arrays in JavaScript?

While JavaScript does not have an inbuilt method to directly compare two arrays, it does have inbuilt methods to compare two strings. Strings can also be compared using the equality operator. Therefore, we can convert the arrays to strings, using the Array join() method, and then check if the strings are equal.

How will you find the difference between two array using array function explain?

The array_diff() function compares the values of two (or more) arrays, and returns the differences. This function compares the values of two (or more) arrays, and return an array that contains the entries from array1 that are not present in array2 or array3, etc.


2 Answers

There is a better way using ES7:


Intersection

 let intersection = arr1.filter(x => arr2.includes(x)); 

Intersection difference Venn Diagram

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)); 

Right difference Venn Diagram

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))); 

Symmetric difference Venn Diagram

This way, you will get an array containing all the elements of arr1 that are not in arr2 and vice-versa

As @Joshaven Potter pointed out on his answer, you can add this to Array.prototype so it can be used like this:

Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); } [1, 2, 3].diff([2, 3]) 
like image 128
Luis Sieira Avatar answered Oct 11 '22 10:10

Luis Sieira


Array.prototype.diff = function(a) {     return this.filter(function(i) {return a.indexOf(i) < 0;}); };  ////////////// // Examples // //////////////  const dif1 = [1,2,3,4,5,6].diff( [3,4,5] );   console.log(dif1); // => [1, 2, 6]   const dif2 = ["test1", "test2","test3","test4","test5","test6"].diff(["test1","test2","test3","test4"]);   console.log(dif2); // => ["test5", "test6"]

Note .indexOf() and .filter() are not available before IE9.

like image 39
Joshaven Potter Avatar answered Oct 11 '22 10:10

Joshaven Potter