A slight variation on CertainPerformance's answer:
function arraysAreEqual(arr1, arr2) {
// Check if the arrays have the same length
if (arr1.length != arr2.length) {
// Bail out immediately if they are
return false;
}
const arr1Set = new Set(array1);
const arr2Set = new Set(array2);
// Check Size in case one had duplicates, then use has()
return arr1Set.size == arr2Set.size && arr1.every(item => arr2Set.has(item));
}
The array length check is optional if you don't care at all about duplicates, but this still falls short if you wanted to know if the two arrays have exactly the same set of items regardless of their order.
As a side note, .sort() is a mutating function and a bit slow, if you don't want to sort the arrays you are comparing you would need to clone them first into a new array which adds to the overall cost, but:
function arraysAreEqual(array1, array2) {
// Check if the arrays have the same length
if (array1.length !== array2.length) {
// Bail out immediately if they are
return false;
}
// Sort a copy of the arrays or sort the arrays directly if mutation is allowed
const arr1 = [...array1].sort()
const arr2 = [...array2].sort()
// Iterate over the sorted arrays and check values
for (let i = 0; i < arr1.length; i++) {
if (arr1[i] !== arr2[i]) {
// Bail out as there is difference
return false;
}
}
return true;
}
I stumbled onto this question from a rather minor need to optimize how some arrays were being compared and I needed both to worry about the exact set of values and the distinct values in a few cases. Hopefully this is helpful or someone can give feedback to further optimize my answer.
console.log(JSON.stringify(['a','b','c'].sort()) === JSON.stringify(['b','c','a'].sort())); // true[0,1,1]and[0,1]to pass the test.sortis that it's computationally complex -O(n log n), which is worse thanO(n)