How to compare two arrays
Short answer
Compare the lengths and then every element at the same position:
const equal = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
console.log(equal([1, 2, 3], [1, 2, 3]));
console.log(equal([1, 2, 3], [1, 2, 4]));Output:
true
falseIgnoring order
Sort copies of both arrays and compare them:
const sameItems = (a, b) => {
const x = [...a].sort();
const y = [...b].sort();
return x.length === y.length && x.every((value, index) => value === y[index]);
};
console.log(sameItems(['b', 'a', 'c'], ['c', 'b', 'a']));Output:
trueNested data
For arrays of simple objects you can compare their JSON strings. The order of keys must be the same:
const a = [{ id: 1 }, { id: 2 }];
const b = [{ id: 1 }, { id: 2 }];
console.log(JSON.stringify(a) === JSON.stringify(b));Output:
trueCommon mistake
=== compares arrays by reference: two different arrays are never equal, even with the same contents:
console.log([1, 2] === [1, 2]);Output:
falseFunctions used in this recipe
- Array.prototype.every — Checks that every element of an array passes a test.
- JSON.stringify — Converts a value to a JSON string.
- Array.prototype.includes — Checks whether an array contains a value.