Borislav Hadzhiev
Sat Oct 16 2021·2 min read
Photo by Jake Melara
To check if two arrays have the same elements:
every()
method on the first array and verify that the element on
every iteration is equal to the element at the same index from the other
array.every
method only returns true
if the condition is met for every
array element.const arr1 = ['a', 'b', 'c']; const arr2 = ['a', 'b', 'c']; function areEqual(array1, array2) { if (array1.length === array2.length) { return array1.every((element, index) => { if (element === array2[index]) { return true; } return false; }); } return false; } console.log(areEqual(arr1, arr2)); // 👉️ true
We first check if the arrays have the same length, if they don't, we return
false
straight away.
The function we pass to the Array.every method gets invoked with each element in the array until it returns a falsy value or iterates over the entire array.
On each iteration, we check if the current element is equal to the element at the same index from the other array.
every
method returns true
, only if the test function returns a truthy value on all iterations, otherwise it returns false
.If the test function returns false
, the every
method short-circuits and
returns false
.
areEqual
function only returns true
if the passed in arrays have the same length and their values are equal and in the same order.In this example, we call the areEqual
function with two arrays containing the
same elements in a different order and the function returns false
.
const arr1 = ['c', 'b', 'a']; const arr2 = ['a', 'b', 'c']; function areEqual(array1, array2) { if (array1.length === array2.length) { return array1.every((element, index) => { if (element === array2[index]) { return true; } return false; }); } return false; } console.log(areEqual(arr1, arr2)); // 👉️ false
If you don't care about the ordering of the elements and you just want to check if two arrays contain the same elements, use this approach instead.
const arr1 = ['c', 'b', 'a']; const arr2 = ['a', 'b', 'c']; function areEqual(array1, array2) { if (array1.length === array2.length) { return array1.every(element => { if (array2.includes(element)) { return true; } return false; }); } return false; } console.log(areEqual(arr1, arr2)); // 👉️ true
Instead of checking if the current element is equal to the element of the other array with the same index, we just check if the element is included in the other array.