Array Comparison
Data Structures
Algorithm Optimization
Programming
Code Efficiency

Efficient way to compare two arrays

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Introduction

There is no single best way to compare two arrays until you define what “equal” means. Sometimes you care about exact element-by-element equality, sometimes you only care that both arrays contain the same values, and sometimes duplicates matter while order does not.

Choose the Right Definition of Equality

Before picking an algorithm, answer these questions:

  • Must elements appear in the same order
  • Do duplicate values matter
  • Are the elements primitives or objects
  • Is extra memory acceptable

If the arrays must match exactly by index, the fastest correct solution is usually a single linear pass. If order does not matter, you often need sorting or a frequency table instead.

Exact Equality in O(n)

When order matters, compare lengths first and then compare each slot once. That is optimal for most in-memory arrays because every element must be checked at least once in the worst case.

javascript
1function arraysEqual(a, b) {
2  if (a.length !== b.length) {
3    return false;
4  }
5
6  for (let i = 0; i < a.length; i += 1) {
7    if (a[i] !== b[i]) {
8      return false;
9    }
10  }
11
12  return true;
13}
14
15console.log(arraysEqual([1, 2, 3], [1, 2, 3]));
16console.log(arraysEqual([1, 2, 3], [3, 2, 1]));

This runs in O(n) time and O(1) extra space. It is hard to beat when exact positional equality is the goal.

For arrays of objects, strict equality compares references, not contents. In that case, you need a property-based comparison or serialization strategy that matches your data model.

Same Values Without Respecting Order

If order does not matter but duplicates do, a frequency map is usually the best general solution. It avoids the O(n log n) cost of sorting and handles repeated values correctly.

javascript
1function sameMultiset(a, b) {
2  if (a.length !== b.length) {
3    return false;
4  }
5
6  const counts = new Map();
7
8  for (const value of a) {
9    counts.set(value, (counts.get(value) || 0) + 1);
10  }
11
12  for (const value of b) {
13    const current = counts.get(value);
14    if (!current) {
15      return false;
16    }
17
18    if (current === 1) {
19      counts.delete(value);
20    } else {
21      counts.set(value, current - 1);
22    }
23  }
24
25  return counts.size === 0;
26}
27
28console.log(sameMultiset([1, 2, 2, 3], [2, 3, 2, 1]));
29console.log(sameMultiset([1, 2, 2], [1, 1, 2]));

This approach is O(n) time on average with O(n) extra space.

When Sorting Is Good Enough

Sorting is simpler to read and can be perfectly reasonable if:

  • the arrays are small
  • you are already sorting for another reason
  • mutating a copy is acceptable
  • the implementation cost matters more than squeezing out the last bit of performance
javascript
1function sameValuesSorted(a, b) {
2  if (a.length !== b.length) {
3    return false;
4  }
5
6  const sortedA = [...a].sort((x, y) => x - y);
7  const sortedB = [...b].sort((x, y) => x - y);
8
9  return arraysEqual(sortedA, sortedB);
10}
11
12console.log(sameValuesSorted([4, 1, 3], [3, 4, 1]));

The tradeoff is O(n log n) time, plus the cost of copying if you do not want to mutate the original arrays.

Comparing Arrays of Objects

Arrays of objects require more care because two distinct objects with the same fields are not equal by reference.

If you have stable IDs, compare by those IDs:

javascript
1function sameUsersById(a, b) {
2  return sameMultiset(
3    a.map(user => user.id),
4    b.map(user => user.id)
5  );
6}
7
8const left = [{ id: 10, name: "Ana" }, { id: 20, name: "Bo" }];
9const right = [{ id: 20, name: "Bo" }, { id: 10, name: "Ana" }];
10
11console.log(sameUsersById(left, right));

That is usually better than serializing full objects, because object key order and irrelevant fields can make string-based comparisons misleading.

Common Pitfalls

The biggest mistake is using the wrong definition of equality. A fast algorithm is still wrong if it ignores duplicates, ignores order, or compares object references when you meant to compare contents.

Another common issue is sorting arrays in place. If the original order matters elsewhere in the program, an in-place sort creates subtle bugs. Copy before sorting unless mutation is intentional.

Developers also sometimes use nested loops for unordered comparison, which turns the problem into O(n²). That may be fine for tiny arrays, but it scales poorly.

Finally, be careful with floating-point data. Values that are conceptually the same can differ by tiny rounding errors, so direct equality may be too strict.

Summary

  • Define equality before choosing an algorithm.
  • Exact positional comparison is usually a single O(n) pass.
  • For unordered arrays with duplicates, use a frequency map.
  • Sorting is simpler but usually slower at O(n log n).
  • For object arrays, compare stable keys or relevant fields, not raw references.

Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.