EN
JavaScript - check if arrays are identical
0
points
In this article, we would like to show you how to check if arrays are identical in JavaScript.
Practical example
To check if arrays are identical we take the following steps:
- Check if the
lengthof both arrays is the same (if it's not they are different), - iteratively check each element to find out if they are equal.
// ONLINE-RUNNER:browser;
function areEqual(array1, array2) {
if (array1 === array2) {
return true;
}
if (array1.length !== array2.length) {
return false;
}
for (var i = 0; i < array1.length; ++i) {
if (array1[i] !== array2[i]) return false;
}
return true;
}
// Usage example
console.log(areEqual([1, 2, 3], [1, 2, 3])); // true
console.log(areEqual([1, 2, 3], [3, 2, 1])); // false
ES6 version
In this section, we've used JavaScript modern syntax.
// ONLINE-RUNNER:browser;
const areEqual = (array1, array2) => {
if (array1 === array2) return true;
if (array1.length !== array2.length) return false;
for (let i = 0; i < array1.length; ++i) {
if (array1[i] !== array2[i]) return false;
}
return true;
};
// Usage example
console.log(areEqual([1, 2, 3], [1, 2, 3])); // true
console.log(areEqual([1, 2, 3], [3, 2, 1])); // false