Encodera

Thanks for reading!

Donate to the site — we work hard for you.

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
false

Ignoring 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:

true

Nested 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:

true

Common mistake

=== compares arrays by reference: two different arrays are never equal, even with the same contents:

console.log([1, 2] === [1, 2]);

Output:

false

Functions used in this recipe

Thanks for reading!

Donate to the site — we work hard for you.