Comparing if 2 arrays are the same is something that we’ve to do sometimes in our JavaScript app.
In this article, we’ll look at how to compare arrays with JavaScript.
Array.prototype.every
We can use the array’s every
method to check if every element in one array is also in the array we’re comparing against.
If they have the same length and each element in one array is also in the other, then we know that both arrays are the same.
For example, we’ll write:
const array1 = [1, 2, 3]
const array2 = [1, 2, 3]
const sameArray = array1.length === array2.length && array1.every((value, index) => value === array2[index])
console.log(sameArray)
We have 2 array array1
and array2
that have the same contents.
Then we check if both have the same length.
And then we call every
with the callback to compare value
with array2[index]
.
value
has the array1
entry we’re iterating through.
index
has the index of the array1
entry we’re iterating through.
And so we can use index
to get the element from array2
and compare them.
Lodash isEqual Method
We can also use Lodash’s isEqual
method to compare 2 arrays to see if they have the same content.
For instance, we can write:
const array1 = [1, 2, 3]
const array2 = [1, 2, 3]
const sameArray = _.isEqual(array1, array2)
console.log(sameArray)
We just pass in the arrays we want to compare as the arguments.
JSON.stringify
Also, we can do simple array comparisons with the JSON.stringify
method.
It’ll convert the array to a JSON string.
Then we can compare the stringified arrays directly.
For instance, we can write:
const array1 = [1, 2, 3]
const array2 = [1, 2, 3]
const sameArray = JSON.stringify(array1) === JSON.stringify(array2);
console.log(sameArray)
Conclusion
There’re several ways we can use to compare if 2 arrays are the same with JavaScript.
The easiest way is to use JSON.stringify
to compare the stringified versions of the arrays.
Also, we can use the every
method to check each item of an array to see if they’re the same.
Finally, we can use the Lodash isEqual
method to compare 2 arrays.