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:
// ONLINE-RUNNER:browser;
const areEquals = (a, b) => {
if (a === b) {
return true;
}
if (a.length !== b.length) {
return false;
}
for (let i = 0; i < a.length; ++i) {
if (a[i] !== b[i]) {
return false;
}
}
return true;
}
// Usage example:
const a = ['John'];
const b = ['John', 25];
console.log(areEquals(a, a)); // true
console.log(areEquals(b, b)); // true
console.log(areEquals(a, b)); // false
console.log(areEquals(b, a)); // false