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.
To check if arrays are identical we take the following steps:
- Check if the
length
of both arrays is the same (if it's not they are different), - iteratively check each element to find out if they are equal.
xxxxxxxxxx
1
function areEqual(array1, array2) {
2
if (array1 === array2) {
3
return true;
4
}
5
if (array1.length !== array2.length) {
6
return false;
7
}
8
for (var i = 0; i < array1.length; ++i) {
9
if (array1[i] !== array2[i]) return false;
10
}
11
return true;
12
}
13
14
15
// Usage example
16
17
console.log(areEqual([1, 2, 3], [1, 2, 3])); // true
18
console.log(areEqual([1, 2, 3], [3, 2, 1])); // false
In this section, we've used JavaScript modern syntax.
xxxxxxxxxx
1
const areEqual = (array1, array2) => {
2
if (array1 === array2) return true;
3
if (array1.length !== array2.length) return false;
4
5
for (let i = 0; i < array1.length; ++i) {
6
if (array1[i] !== array2[i]) return false;
7
}
8
return true;
9
};
10
11
12
// Usage example
13
14
console.log(areEqual([1, 2, 3], [1, 2, 3])); // true
15
console.log(areEqual([1, 2, 3], [3, 2, 1])); // false