Comparing two arrays in Javascript might seem a bit tricky since the equality operators DO NOT work on them. Well, here’s how you can compare them properly!
You can compare two arrays in Javascript by using a for loop to go over each item and compare them directly against each other. You can also compare two arrays using built-in Javascript methods like the isEqual(), JSON.stringify(), and Array.every() methods.
In this article, we’ll explore all these comparison methods by showing you how you can use them properly in your code.
We’ll also show you how to deal with some interesting edge cases when comparing two arrays in Javascript.
So, let’s get started!
Why Can’t I Compare Two Arrays in Javascript Using the Equality Operator?
The equality operator (==) compares two values for equality. While it may seem like a straightforward way to compare two arrays, using it directly on arrays will not work.
When comparing arrays with the equality operator, it compares the memory reference of the two arrays, rather than their contents.
This means that even if all the elements of the two arrays are the same, the equality operator will return ‘false’ because the memory references are different. This limitation makes the equality operator unreliable for array comparisons.
Unlike primitive data types, objects in Javascript are only considered equal if they reference the same underlying object in memory. So, the equality operator will only return true if both the arrays have the same reference.
Let’s look at an example:
//Primitive datatypes
let name1 = "John"
let name2 = "John"
let age1 = 19
let age2 = 19
console.log(name1 == name2)
console.log(age1 == age2)
//Array Object
let arr1 = [26, 9, 0]
let arr2 = [26, 9, 0]
let arr3 = arr1
console.log(arr1 == arr2)
console.log(arr1 === arr3)
Output:
In the above example, the equality operator rightly returns true for the primitive data type comparisons because they both have the same value.
However, it returns false for the first array comparison even though their contents are the same.
It only returns true when we compare arr1 with arr3 since both of them are pointing to the same space in the memory.
How to Compare Two Arrays in Javascript
Now that we know that the equality operator doesn’t work for comparing arrays, let’s look at the methods that do.
This section will guide you through the basics of comparing arrays, covering essential methods and approaches for determining equality between two arrays.
Here are some of the common ways to compare elements of two arrays:
Using a For Loop
The simplest way to compare two arrays in Javascript is to use a for loop. The loop iterates through both arrays and compares their values one by one. If any pair of elements do not match, you can conclude the arrays are not equal.
To implement this, we first write a check to compare the length of both arrays. If they aren’t equal, then the program returns false right away. Let’s look at an example:
function arr_eq(arr1, arr2){
if (arr1.length !== arr2.length){
return false
}
for(arr in arr1){
if(arr1[arr] !== arr2[arr]){
return false
}
}
return frue
}
const test1 = [3, 4, 6, 7, 8]
const test2 = [3, 4, 6, 7, 8]
console.log(arr_eq(test1, test2))
Output:
true
As we can see it rightly evaluates that both arrays are equal to each other.
Note: Make sure you use the strict equality operator (=== | !== )with this method to avoid incorrectly matching string and number types
Using the Lodash Library
The isEqual() function in the Lodash utility library is a simple and very convenient way you can use to check if two arrays are equal. Here’s how you can use the function:
const _ = require ("lodash");
const arr1 = [1, 2, 3];
const arr2 = [1, 2, 3];
console.log(_.isEqual(arr1, arr2));
Output:
It rightfully shows that both arrays are equal. You can use this function to check for equality on primitive datatypes, arrays, and objects.
Note: The elements in the arrays and objects you are checking have to be in the same order. Also, make sure you have the Lodash module installed by running the following command in your terminal:
npm install lodash
Using the JSON.stringify() Method
Converting both arrays to JSON text using the JSON.stringify() method can be a quick way to compare their content. After converting the arrays to JSON strings, compare them using the strict equality operator, and it will return the result based on the values and order of the elements.
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
console.log(JSON.stringify(arr1) === JSON.stringify(arr2));
Output:
true
This method is efficient and reliable for comparing arrays based on their contents. You can also use this method for object comparison. However, it might not be the best solution for large arrays or complex objects, as it requires converting the entire array structure into a string.
Also, if your arrays contain undefined elements, you’re better off using a different method. This is because the JSON.stringify method doesn’t recognize and convert undefined values. It simply represents them as null.
The same thing happens with function definitions and function calls.
For example:
let arr1 = [undefined, 1, 'Joe']
console.log(JSON.stringify(arr1))
Output:
Using the Array.every() Method
Array.every() is a useful JavaScript method that checks if every element of an array meets certain criteria. To compare two arrays, you can use this method along with a callback function that compares corresponding elements from the arrays, returning a boolean.
This method results in a clean and concise way of comparing both array values and order.
let arr1 = [1, 2, 3];
let arr2 = [1, 2, 3];
let isEqual
if(arr1.length == arr2.length){
isEqual = arr1.every((elem, index) => elem === arr2[index]);
}
else{
isEqual = false
}
console.log(isEqual);
Output:
true
As we can see, it returns true since both arrays have the same elements in the same order.
The Array.every() method is concise, efficient, and works well for small to moderately-sized arrays. However, it might not be the best choice for larger data sets, as the entire comparison runs only if all elements in the array fulfill the given predicate.
Each of these methods has its pros and cons depending on the context, size, and content of the arrays you’re comparing. Choose the method that best suits your specific situation to compare the elements, values, and order of two arrays in JavaScript.
How to Compare Two Nested Arrays in Javascript
Nested arrays are arrays that contain other arrays as their elements. They provide an interesting edge case you might encounter when writing code to compare two arrays.
Here are some ways you can compare them successfully in Javascript:
Using isArray() and Recursion
One way to compare nested arrays is to consider each element in the arrays, and if that element is an array, recursively compare the subarrays. The Array.isArray() method can be used to check if a given variable is an array.
Combining this with a recursive function allows you to traverse and compare nested arrays effectively. Here’s an example:
function compareNestedArrays(arr1, arr2) {
if (arr1.length !== arr2.length) {
return false;
}
for (let i = 0; i < arr1.length; i++) {
if (Array.isArray(arr1[i]) && Array.isArray(arr2[i])) {
if (!compareNestedArrays(arr1[i], arr2[i])) {
return false;
}
} else if (arr1[i] !== arr2[i]) {
return false;
}
}
return true;
}
This function compares the lengths of the arrays first and then iterates through the elements. If it encounters two nested arrays, it calls itself recursively to compare the subarrays. If the elements don’t match, the function returns false; otherwise, it continues with the following elements.
Example usage:
const array1 = [1, [2, 3], 4];
const array2 = [1, [2, 3], 4];
const array3 = [1, [2, 4], 4];
console.log(compareNestedArrays(array1, array2));
console.log(compareNestedArrays(array1, array3));
Output:
In the example above, the function correctly identifies that array1 and array2 are equal while array3 differs due to the nested array.
While this approach works well for most cases, keep in mind that it may not be suitable for extremely large nested arrays or when performance is a concern. Recursive functions can be slower and more memory-intensive. However, for most purposes, this method is clear, efficient, and easy to understand.
Using the Lodash isEqual() Function
The isEqual function does a deep comparison of the two arrays you put into it as arguments. So, you can also use it to compare nested arrays. All you have to do is make sure that the elements in both arrays are in the same order.
The toString() Method
Just like the JSON.stringify() methods, the toString() method can be an effective way to compare two arrays by converting them to strings. This method is available for all JavaScript objects, including arrays.
It converts data types to their string representations, which can then be easily compared.
const array1 = [1, [2, 3], 4];
const array2 = [1, [2, 3], 4];
const array3 = [1, [2, 4], 4];
console.log(array1.toString() == array2.toString());
console.log(array1.toString() == array2.toString());
Output:
true
false
Note that you cannot use this method with arrays containing objects as the object strings will not be returned accurately. Also, keep in mind that this method is best used when data types don’t need to be preserved during the comparison process.
How to Compare Two Unordered Arrays in Javascript
In all of the comparison methods we mentioned above, the order of the array elements is very important. If both arrays contain the same elements, but in a different order, all the comparison methods will return false.
Let’s look at an example with the JSON.stringify() method. While this method allows you to compare arrays by converting them to JSON strings, it assumes that the order of elements in both arrays is the same.
let array1 = [11, 22, 33];
let array2 = [33, 11, 22];
console.log(JSON.stringify(array1) === JSON.stringify(array2));
Output:
We can see the program returns False even when it is clear that both arrays contain the same element. In this situation, an easy solution is to sort the arrays before using JSON.stringify().
array1.sort();
array2.sort();
console.log(JSON.stringify(array1) === JSON.stringify(array2));
Since both Arrays are properly sorted, we get the correct answer which is true. You can apply the sort() function to the arrays before using any of the comparison methods listed in the section above.
Final Thoughts
So, there you have it! Array comparison can be a very simple and short process if you use the right functions and methods. Just be careful and plan properly when writing code to avoid common pitfalls like nested arrays, undefined values, and unordered arrays.
Just make sure you employ the strategies explored in this article properly and you’ll be ready to face any array comparison challenge that comes your way!
If you’re looking for more interesting Javascript content, be sure to check out our article on Comparing Two Dates in JavaScript: A How-To Guide. You can also watch this video to get up to speed on the incoming AI Revolution.
Frequently Asked Questions
How can I deeply compare arrays of objects in JavaScript?
To deeply compare arrays of objects in JavaScript, you can use the JSON.stringify() method. This method converts the arrays into a JSON string, which can then be compared to check for structural and data equivalence.
However, be aware of the edge case where undefined values are not valid JSON, and the order of keys in objects may impact the comparison.
How can I get common elements in two arrays in JavaScript?
To compare two arrays in JavaScript and retrieve their common elements, you can apply the filter() method on one array and pass a callback function that checks if the current element exists in the other array. For example:
const array1 = [1, 2, 3];
const array2 = [2, 3, 4];
const commonElements = array1.filter((elem) => array2.includes(elem));
console.log(commonElements)
Output:
When you run the code, it returns an array containing the common elements between the two input arrays.
Which Array Comparison Method is the Fastest?
The fastest comparison methods are the native methods like the for loop and the JSON.stringify() methods. However, for more complex and nested arrays, you might want to consider using the Lodash isEqual() method.