Sometimes, we want to check if two arrays have the same values with JavaScript.
In this article, we’ll look at how to check if two arrays have the same values with JavaScript.
How to check if two arrays have the same values with JavaScript?
To check if two arrays have the same values with JavaScript, we can use the array every
method.
For instance, we write
const set1 = new Set(arr1);
const set2 = new Set(arr2);
return (
arr1.every((item) => set2.has(item)) && arr2.every((item) => set1.has(item))
);
to convert arrays arr1
and arr2
to sets.
And then we call arr1.every
with a callback to see if set2
has the item
in arr1
.
Then we call arr2.every
with a callback to see if set1
has the item
in arr2
.
If both every
call return true
, then both arrays have the same values.
Conclusion
To check if two arrays have the same values with JavaScript, we can use the array every
method.