When working with JavaScript, we often come across situations where we need to compare two arrays to check if they are equal or not. In this article, we will cover various methods to compare two arrays in JavaScript using conversion to strings, looping through array elements, and using external libraries.
5 Ways to Compare Two Arrays in JavaScript
We can compare any two values in JavaScript by “==” and “===”, but this is not applicable here because the datatype of an array is an object, and when comparing objects the equality operators check for reference equality rather than value equality.
Let’s explore methods to compare two arrays. It’s important to note that each method may have some drawbacks, therefore we have to choose the best method according to our use case.
1) JSON.stringify()
The simplest way to compare two arrays in JavaScript is by converting an array into a JSON string, making them ready for comparison directly.
For example:
// Declare three arrays let arr1 = [1,2,4,5]; let arr2 = [1,2,3,4]; let arr3 = [1,2,4,5]; // Comparing using stringify method console.log(JSON.stringify(arr1) === JSON.stringify(arr2)); console.log(JSON.stringify(arr1) === JSON.stringify(arr3));
Output:
false
true
We can successfully compare two arrays with this method. However, some points to keep in mind are:
As this method converts JavaScript objects(including arrays) to JSON-formatted strings, therefore null and undefined both are represented as null. We should avoid this method if we want to treat null and undefined distinctly.
This method works well for basic data types like strings, numbers, and objects. However, it does not support custom objects with methods like Map, Set, or arrays that contain functions.
2) Using .toString()
The .toString() method converts any data types, including objects to a string representation which can then be compared directly.
// Declare three arrays let arr1 = [1,2,4,5]; let arr2 = [1,2,3,4]; let arr3 = [1,2,4,5]; // Comparing using .toString method console.log(arr1.toString() === arr2.toString()); console.log(arr1.toString() === arr3.toString());
Output:
false
true
However JSON.stringify() is preferred over .toString() because of following reasons:
`JSON.stringify` preserves the structure of the array. It serializes the array into a string without altering its original shape. This is important when dealing with nested arrays or arrays of objects.
When an array contains nested arrays or objects, `JSON.stringify` recursively serializes, whereas .toString() simply converts the array to a comma-separated string, which leads to loss of hierarchical information. For example:
// Original array with different data types and nested structures let array = [1, [2, 3], { key: 'value' }]; // using .toString() method on the array console.log(array.toString()); // using JSON.stringify() method on the array console.log(JSON.stringify(array));
Output:
"1,2,3,[object Object]"
"[1,[2,3],{"key":"value"}]"
Therefore `JSON.stringify` provides a more accurate and complete representation of the array, including nested arrays and objects.
3) Using every()
This is an example of looping over the array, we can compare each element of an array to the corresponding element in the other array. In the every() method, a callback function is executed for each element in an array, which receives the current element, its index, and the array as parameters.
We will first check the length of both arrays because if the length is not the same, then no need to check the whole array. Here is an example:
// Function to compare two arrays element-wise const comparison = (arrayA, arrayB) => { // Check if the lengths of the arrays are equal // and if every corresponding value in the arrays is identical return ( arrayA.length === arrayB.length && arrayA.every((value, index) => value === arrayB[index]) ); }; // Example arrays for testing the comparison function let array1 = [1, 2, 3, null]; let array2 = [2, 2, 3, 4]; let array3 = [1, 2, 3, undefined]; // Testing the comparison function with example arrays console.log(comparison(array1, array2)); console.log(comparison(array1, array3));
Output:
false
false
4) Using a for Loop
This method involves manually iterating over each element of the arrays and comparing them one by one. It uses a for loop in combination with if statements. This is an easy method for beginners and provides more control over the comparison process.
function comparison(array1, array2) { // Check if the arrays have the same length if (array1.length !== array2.length) { return false; } // Iterate through the elements of the arrays for (let i = 0; i < array1.length; i++) { // Compare the current elements if (array1[i] !== array2[i]) { return false; } } // If the loop completes without returning false, the arrays are equal return true; } // Example arrays for testing the comparison function let Array1 = [1, 2, 3, null]; let Array2 = [1, 2, 3, 4]; let Array3 = [1, 2, 3, Undefined]; let Array4 = [1, 2, 3, 4]; // Testing the comparison function with example arrays console.log(comparison(Array1, Array2)); console.log(comparison(Array1, Array3)); console.log(comparison(Array2, Array4));
Output:
false
false
true
Here after comparing lengths, we compared each element at the corresponding index. If any pair of elements is not equal, the function returns false. If all the elements pass the comparison, true is returned.
But we have to keep in mind for comparing more complex scenarios, especially involving nested arrays or objects, we may need to implement additional custom logic.
5) Using Lodash _.isEqual()
If you prefer using external libraries, Lodash provides a convenient method known as isEqual() to compare two arrays. We first need to import the _.isEqual() library.
The Lodash _.isEqual() method performs a deep comparison, which is beneficial when we are comparing arrays in a more complex scenario such as when the arrays contain objects or nested arrays.
// Importing isEqual method from lodash const _ = require('lodash'); // Example arrays const Array1 = [1, 2, 3]; const Array2 = [1, 2, 3]; const array3 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]; const array4 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Charlie' }]; //Checking for equal values console.log(_.isEqual(Array1,Array2)); console.log(_.isEqual(Array3,Array4));
Output:
true
false
This method can be a convenient and reliable way to compare arrays, especially in cases when we have complex data structures.
Conclusion
We have successfully covered various methods to compare two arrays in JavaScript, with their advantages and limitations. Therefore which method to opt for will depend on the use case. Now you can learn to Sort an Array of Objects in JavaScript.