📋 Table Of Content
- The length of both the arrays should be same.
- The items in both the arrays must be of same type.
- The items in both arrays should be of same order number. (Optional)
Using JSON.stringify() method to compare arrays
Here, we will use stringify to convert both arrays to strings and then compare them for equality.
let arr1 = [1, 2, 3, 4]; let arr2 = [1, 2, 3, 4]; let isEqual = JSON.stringify(arr1) === JSON.stringify(arr2); console.log(isEqual);
Using toString() method to compare arrays in JS
toString() method is use to convert any number to a string.
We can use toString() to convert the arrays to strings and compare them.
Let's see an example:
let arr1 = [1, 2, 3, 4]; let arr2 = [1, 2, 3, 4]; let isEqual = arr1.toString() === arr2.toString(); console.log(isEqual);
If it satisfies the given condition, it will return
true, else it will return
Lets see every() in action:
let arr1 = [1, 2, 3, 4]; let arr2 = [1, 2, 3, 4]; let isEqual = arr1.length === arr2.length && arr1.every((val, index) => val === arr2[index]); console.log(isEqual);
JSON.stringify(), toString() and every(), all these methods will not work or will return false, if the order of the items in both arrays are different.
Example: [1, 2, 3, 4] and [2, 1, 3, 4] will return false when compared.
So if you want to compare two arrays with out of order elements check the solution below.
Compare Two Arrays Regardless of Orders
To compare two arrays with elements in different orders, we will use every() and includes() method together.
Array.includes() method check if certain element is present or not in a given array.
Let's see an example where we first check if the length of the arrays are same or not and then check if the arrays have same elements regardless of the order.
let arr1 = [1, 2, 3, 4]; let arr2 = [1, 2, 4, 5]; let isEqual = arr1.length === arr2.length && arr1.every((val, index) => arr2.includes(val)); console.log(isEqual);
In the above code, you can see even if the order of the elements in the arrays are different it have return
Using Lodash and Underscore library
Lets see how to use lodash to compare two arrays:
let arr1 = [1, 2, 3, 4]; let arr2 = [1, 2, 3, 4]; console.log(_.isEqual(arr1,arr2)) // true
In Lodash too, order of the element matters.
_.isEqual([1, 2, 3] , [3, 2, 1]) // false
It will return false.
So to solve this issue, we can sort the array first and then compare it. Example:
_.isEqual([1, 2, 3].sort(),[3, 2, 1].sort()) // true