EN
JavaScript - shallow compare of arrays
13 points
In this article, we would like to show you how to do shallow compare of arrays in JavaScript.
As shallow compare operation we understand elements comparison only on first arrays level.
Practical example:
xxxxxxxxxx
1
const areEquals = (a, b) => {
2
if (a === b) {
3
return true;
4
}
5
if (a.length !== b.length) {
6
return false;
7
}
8
for (let i = 0; i < a.length; ++i) {
9
if (a[i] !== b[i]) {
10
return false;
11
}
12
}
13
return true;
14
}
15
16
17
// Usage example:
18
19
const a = ['John'];
20
const b = ['John', 25];
21
22
console.log(areEquals(a, a)); // true
23
console.log(areEquals(b, b)); // true
24
25
console.log(areEquals(a, b)); // false
26
console.log(areEquals(b, a)); // false