How to Get Difference Between Two Arrays in JavaScript

JavaScript developers need to commonly work with arrays. While doing so, they need to get the difference between two arrays. There can be various types of differences between arrays, such as checking if they are equal, finding common elements, or getting elements present in one but not the other. Since arrays are reference types of data, it can be difficult for beginners to solve this problem. In this article, we will learn how to difference between two arrays in JavaScript.

How to Get Difference Between Two Arrays in JavaScript

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

1. Using Equality Operators

Typically, we use equality operators such as ‘==’ or ‘===’ to check if two variables are equal or not. Here is an example.

a=1;
b=1;
console.log(a===b); // output is true

However, they do not work for arrays, since two arrays have different references even if they contain the same elements.

c=[1, 2, 3];
d=[1, 2, 3];
console.log(c===d); // output is false
console.log(c==d); // output is false

On the other hand, only if you explicitly assign one variable to another, then you can use this operator to check equality between arrays. This is because in this case, they refer to the same object in memory.

c=[1, 2, 3];
e=c;
console.log(c===e); // output is true

2. Using JSON.stringify

In this solution, we convert the JavaScript arrays into strings and compare the string representations for equality. For this purpose, we use JSON.stringify() function. If two arrays are identical, their string representations will be identical.

c=[1, 2, 3];
d=[1, 2, 3];
console.log(JSON.stringify(c) === JSON.stringify(d)); // output is true

This approach works only if your arrays are simple (not nested arrays or arrays with references), and have same order of elements. Even if the arrays have same items in different order this solution will not work.

c=[1, 2, 3];
d=[1, 3, 2];
console.log(JSON.stringify(c) === JSON.stringify(d)); // output is false

3. Using toString

Similarly, you can also use toString() available for all JS variables and literals. It converts the data into string. In this case, toString() converts array into string, which can then be compared using equality operators.

c=[1, 2, 3];
d=[1, 2,3];
console.log(c.toString() === d.toString()); // output is true

4. Using Every() function

In this case, we check each pair of items in both arrays at every index. First, you need to check if both arrays have same length.

c=[1, 2, 3];
d=[1, 2, 3];
if(c.length==d.length){
console.log(c.every((value, index) => value === d[index]));
}

In the above code, every() function loops through the first array and for each array item, it checks if the corresponding value of the second array is equal to it.

5. Using for loop

Sometimes the array items themselves are complex objects instead of simple data types such as numbers and strings. In such cases, you need to do a recursive comparison. Here is an example.

function check_equal(a, b) {
if (a.length !== b.length) return false;

for (let i = 0; i < a.length; i++) {
const val1 = a[i];
const val2 = b[i];

const areObjects = typeof val1 === 'object' && typeof val2 === 'object';
if (areObjects && !check_equal(val1, val2)) return false;
if (!areObjects && val1 !== val2) return false;
}
return true;
}

console.log(check_equal([1, [2, 3]], [1, [2, 3]])); // Output: true
console.log(check_equal([1, [2, 3]], [1, [3, 2]])); // Output: false

In the above code, we have defined check_equal recursive function. First, it checks if the lengths of the two arrays are equal. If not, then it returns false. Else it loops through the arrays in parallel, comparing pairs of corresponding items, one pair at a time.

While comparing a pair of items from the two arrays, it checks if the two items are objects. If so, then it recursively calls check_equal function on them too. Its result is used to decide whether the two object items are equal or not.

First it checks if the two items are objects but unequal then return false. If they are not objects and not equal either, then also return false. Otherwise, return true.

Using for loop is one of the most basic ways to check array difference. But it provides the most customization options, as we can see above.

6. Using Filter

JavaScript arrays support filter function that tests each item of an array and returns items that pass the test. You can use it in different ways to compare two arrays.

We will first learn how to use filter function to get common items in two arrays. In other words, we get the intersection of two arrays. JavaScript provides includes function to help you check if an item is present in an array. It returns true if the item is present, else it returns false. We will use this function to get all the common items in two arrays.

c=[1, 2, 3];
d=[3, 4, 5];
console.log(c.filter(el => d.includes(el)))

In the above code, we call filter() function on first array. In the filter function that runs for each item of first array, we check if each item is present in second array, using includes() function.

You can also use this same logic to check if the two arrays are equal. If they are equal then the result of filter function is same as either of the two arrays.

There are two ways to calculate difference between two arrays – symmetric and asymmetric. In symmetric difference, we find the items that are not common to the two arrays. In other words, they are present in either of the two arrays but not in both arrays.

In asymmetric difference, we find the items that are present in one of the arrays but not the other array.

Let us look at both these differences one by one. Here is an example of asymmetric difference.

c=[1, 2, 3];
d=[1, 2, 4];

console.log(c.filter(el => !d.includes(el))); // output is [3]

In the above code, we call filter function on array c. In this, we test each element of array c to see if it is NOT present in array d. The filter function will return [3] since it is present only in array c.

c=[1, 2, 3];
d=[1, 2, 4];

console.log(d.filter(el => !c.includes(el))); // output is [4]

In the above code, we interchange c and d, to get items that are present in array d but not in array c. The filter function will return [4] since it is present only in array d.

Here is an example of symmetric difference in two arrays. In the following code, we basically concatenate the result of the above two asymmetric differences, using concat() function.

console.log(c.filter(el => !d.includes(el)).concat(d.filter(el => !c.includes(el)))); // output is [3, 4]

7. Using Set

In the previous solutions, the order of array items is important. Even if two arrays have identical items but in different orders then the above solutions will return false. In such cases, you can convert the arrays into sets and compare them. By definition, the order of items does not matter.

c=[1, 2, 3];
d=[1, 2, 4];
console.log(new Set(c).size === new Set(d.filter(el => c.includes(el))).size); // output is false

c=[1, 2, 3];
d=[3, 1, 2];
console.log(new Set(c).size === new Set(d.filter(el => c.includes(el))).size); // output is true

In the above code, we first obtain an array of all items in second array, that are present in first array. For this, we use filter() function. We construct a set using the result array. We also construct another set using the first array. We compare the number of items of both the sets, using their size attributes.

8. Using Lodash

Lodash is a popular JavaScript library that allows you to work with arrays and other parts of your web data. It contains isEqual() function that allows you to compare two arrays. It is a comprehensive function that even compares objects, references and nested arrays.

const _ = require('lodash');

console.log(_.isEqual([1, 2, 3], [1, 2, 3])); // output is true
console.log(_.isEqual([1, [2, 3]], [1, [3, 2]])); // output is false

Conclusion

In this article, we have learnt several different ways to get difference between two arrays in JavaScript. If the order of items in two arrays is not the same, then you can convert them into Set and compare them to get the result. If two arrays have same order for most or all items, then you can use toString or JSON.stringify to convert them into strings and comparing the two string representations. If you want to get items present in one array but not the other, then you can calculate asymmetric or symmetric difference, using filter() function.

FAQs

1. How to get asymmetric difference between two arrays?

You can use filter function for this purpose. Test if each item of one array is present in the other array using includes() function.

c=[1, 2, 3];
d=[1, 2, 4];

console.log(c.filter(el => !d.includes(el))); // output is [3]

2. How to get array difference if the order of items are different in both arrays but they contain same items?

In this case, you can convert the arrays into Sets and compare the two sets for equality. Sets contain unique items in unordered manner.

c=[1, 2, 3];
d=[3, 1, 2];
console.log(new Set(c).size === new Set(d.filter(el => c.includes(el))).size); // output is true

Also read:

How to Remove Character from String in JS
How to Replace All Occurrences of Substring in JS
How to Check Whether String Contains Substring in JS

Leave a Reply

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