array difference in js

How to Get Difference Between Two Arrays in JavaScript

JavaScript allows you to easily store data in arrays. It is a commonly used data structure by developers. But often you may need to find difference between two arrays. In other words, you may need to find out elements present in one array but not the other. In this article, we will learn how to get difference between two arrays in JavaScript.


How to Get Difference Between Two Arrays in JavaScript

Here are the steps to get difference between two arrays in JavaScript.

Let us say you have the following 2 arrays.

var a1 = ['a', 'b'];
var a2 = ['a', 'b', 'c', 'd'];

and you need the difference between two arrays as [‘c’, ‘d’]

You can easily get this information using JS filter function that iterates through the given arrays to create a new array that satisfies a given condition. In our case, we need to create an array of elements that are present in a2 but not in a1. You can do this using the following command.

a3 = a2.filter(x => !a1.includes(x));

In the above filter function we iterate through each element of a2 and test if it is present in a1 (using includes() function).

Here is the output you will get on running the above code.

console.log(a3);
['c','d']

Pleas note that you need to iterate through the larger array and test if its elements are present in the smaller array and not the other way round.

You can create a prototype function so that it is available for all arrays, as shown below.

Array.prototype.diff = function(arr2) { return this.filter(x => !arr2.includes(x)); }

Now you should be able to directly call the function on any array.

[1, 2, 3].diff([2, 3]);
//[1]

The above function calculates only asymmetric difference but not a complete of symmetric difference. For example, you get the same output [1] if you take difference of [1,2,3] with [2,3] as well as [1,2,3] with [2,3,5].

If you want the difference of [1,2,3] with [2,3,5] to be [1,5] you need to alter your filter function as shown below.

let a3 = a2.filter(x => !a1.includes(x)).concat(a1.filter(x => !a2.includes(x)));
console.log(a3);//[1,5]

In the above case, we take difference of a1 with a2 and vice versa and concatenate the results to obtain symmetric difference.

In this article, we have learnt the difference between two arrays in JavaScript.

Also read:

How to Compare Dictionary in Python
How to Compare Objects in JavaScript
How to Group By Array of Objects By Key
How to Find Element Using XPath in JavaScript
How to Remove Submodule in Git

Leave a Reply

Your email address will not be published. Required fields are marked *