search ]

Comparing Arrays in JavaScript and jQuery (With Examples)

Comparing two arrays in JavaScript or jQuery might seem simple, but there’s more to it than just using == or ===. Arrays are reference types, meaning even if two arrays contain the same values, they aren’t equal unless they reference the exact same object.

If you’re checking whether two arrays contain the same values in the same order, you need to compare them element by element.

In this post, we’ll explore how to compare arrays accurately using both JavaScript and jQuery. You’ll learn where built-in methods fall short, and how to handle both primitive values and complex structures. If you’re new to arrays, check out our complete guide to JavaScript arrays.

Comparing Arrays in JavaScript

JavaScript offers several practical ways to compare arrays, depending on whether you’re working with primitive values, objects, or care about order. These techniques are also helpful when you’re filtering arrays or performing data validation.

Why == and === Don’t Work

Let’s start with an example that shows why reference comparison fails:

const a = [1, 2, 3];
const b = [1, 2, 3];

console.log(a === b); // false

Although both arrays have identical values, they are two different objects in memory. That’s why this returns false.

Compare Arrays with Length and every()

The most common way to compare arrays in JavaScript is to:

  • Check if their lengths are equal
  • Compare each element one by one using every()
function arraysEqual(a, b) {
  return a.length === b.length && a.every((val, index) => val === b[index]);
}

const x = [1, 2, 3];
const y = [1, 2, 3];

console.log(arraysEqual(x, y)); // true

This method works well for flat arrays containing primitive values. For more on working with array methods like every(), visit our array guide.

Quick Comparison Using JSON.stringify()

Another simple way to compare flat arrays is by converting them to strings:

const a = [1, 2, 3];
const b = [1, 2, 3];

console.log(JSON.stringify(a) === JSON.stringify(b)); // true

This approach works only when:

  • The arrays are flat (no nested objects)
  • The order of elements matters

Be aware that JSON.stringify() silently drops undefined values and functions, converts NaN to null, and is sensitive to object key order. For example, JSON.stringify({a: 1, b: 2}) and JSON.stringify({b: 2, a: 1}) produce different strings even though the objects are logically equal.

Compare Arrays Without Considering Order

If the order of elements doesn’t matter, sort copies of both arrays before comparison:

function unorderedEqual(a, b) {
  if (a.length !== b.length) return false;
  const sortedA = [...a].sort();
  const sortedB = [...b].sort();
  return sortedA.every((val, index) => val === sortedB[index]);
}

console.log(unorderedEqual([1, 2, 3], [3, 2, 1])); // true

Note the use of the spread operator ([...a]) to create copies before sorting. This avoids mutating the original arrays. Learn more about sorting in our guide to sorting arrays in JavaScript.

Comparing Arrays of Objects

For basic comparison of object arrays, you can use JSON.stringify() – as long as the object keys are in the same order:

const a = [{ id: 1 }, { id: 2 }];
const b = [{ id: 1 }, { id: 2 }];

console.log(JSON.stringify(a) === JSON.stringify(b)); // true

Use this approach only when key order is guaranteed to match between objects.

For a more reliable comparison of arrays with nested objects, you can write a recursive deep-equal function:

function deepEqual(a, b) {
  if (a === b) return true;
  if (typeof a !== typeof b) return false;
  if (Array.isArray(a) && Array.isArray(b)) {
    if (a.length !== b.length) return false;
    return a.every((val, i) => deepEqual(val, b[i]));
  }
  if (typeof a === 'object' && a !== null && b !== null) {
    const keysA = Object.keys(a);
    const keysB = Object.keys(b);
    if (keysA.length !== keysB.length) return false;
    return keysA.every(key => deepEqual(a[key], b[key]));
  }
  return false;
}

const x = [{ id: 1, meta: { active: true } }];
const y = [{ id: 1, meta: { active: true } }];

console.log(deepEqual(x, y)); // true

This handles nested objects and arrays regardless of key order matching.

Comparing Arrays Using a Set

If you only need to know whether two arrays contain the same unique values (ignoring order and duplicates), you can use a Set:

function sameValues(a, b) {
  const setA = new Set(a);
  const setB = new Set(b);
  if (setA.size !== setB.size) return false;
  return [...setA].every(val => setB.has(val));
}

console.log(sameValues([1, 2, 3], [3, 1, 2]));    // true
console.log(sameValues([1, 2, 2], [1, 2]));         // true (duplicates ignored)

This is useful for checking membership equality, but it doesn’t account for duplicate counts. If you need to compare duplicates accurately, check out our post on removing duplicates from arrays.

Comparing Arrays in jQuery

jQuery doesn’t provide a built-in method for array comparison, but you can still achieve it by combining jQuery helpers like $.each() with standard JavaScript logic. If you’re already using jQuery for DOM interaction or event handling, these methods will integrate smoothly into your code.

jQuery Approach with $.each and Manual Checks

Here’s how you can compare two arrays by looping through each item and checking values manually:

function arraysEqual(a, b) {
  if (a.length !== b.length) return false;

  var equal = true;
  $.each(a, function(index, value) {
    if (value !== b[index]) {
      equal = false;
      return false; // break loop
    }
  });

  return equal;
}

var a = [1, 2, 3];
var b = [1, 2, 3];

console.log(arraysEqual(a, b)); // true

Ignoring Order in jQuery

If the order of elements doesn’t matter, sort copies of both arrays before comparing them:

function unorderedEqual(a, b) {
  if (a.length !== b.length) return false;

  var sortedA = a.slice().sort();
  var sortedB = b.slice().sort();

  var equal = true;
  $.each(sortedA, function(index, value) {
    if (value !== sortedB[index]) {
      equal = false;
      return false;
    }
  });

  return equal;
}

console.log(unorderedEqual([3, 2, 1], [1, 2, 3])); // true

Comparing Arrays of Objects in jQuery

For comparing arrays of objects, you can still use JSON.stringify() in jQuery-based projects:

var a = [{ id: 1 }, { id: 2 }];
var b = [{ id: 1 }, { id: 2 }];

console.log(JSON.stringify(a) === JSON.stringify(b)); // true

This works only if the structure and key order are identical.

Which Method Should You Use?

Here’s a quick reference for choosing the right approach:

  • Flat arrays, order matters – Use every() with length check. Simple, fast, and reliable.
  • Quick and simple – Use JSON.stringify(). Easy to write, but be careful with edge cases like undefined, NaN, and key order in objects.
  • Order doesn’t matter – Sort copies first, then compare. Use the spread operator or slice() to avoid mutating the originals.
  • Nested objects or arrays – Write a recursive deep-equal function or use a battle-tested library like Lodash (_.isEqual()).
  • Unique membership only – Use a Set-based comparison when duplicates don’t matter.
  • jQuery projects – Use $.each() with manual checks if you’re already in a jQuery codebase.

FAQs

Why does [1,2,3] === [1,2,3] return false in JavaScript?
Arrays in JavaScript are objects, and objects are compared by reference, not by value. Even if two arrays contain identical elements, they occupy different locations in memory, so === returns false. To compare their contents, you need to check each element individually using methods like every() or JSON.stringify().
Is JSON.stringify() a reliable way to compare arrays?
JSON.stringify() works well for flat arrays with primitive values. However, it has limitations: it drops undefined values and functions, converts NaN to null, and is sensitive to object key order. For nested structures or when key order may vary, use a recursive deep-equal function or a library like Lodash instead.
How do I compare two arrays without caring about order?
Sort copies of both arrays first, then compare element by element. Use the spread operator ([...arr].sort()) or slice() to avoid mutating the originals. If you only care about unique membership without duplicate counts, you can use a Set-based approach instead.
Can I use Lodash or other libraries to compare arrays?
Yes. Lodash's _.isEqual() performs a deep comparison of two values and handles all edge cases including nested objects, arrays, NaN, and different key orders. It's a solid choice for production code where you need reliable deep equality checks without writing your own recursive function.
Does sort() modify the original array when comparing?
Yes, sort() mutates the original array in place. Always create a copy before sorting if you want to preserve the original order. Use [...arr].sort() (spread operator) or arr.slice().sort() to sort a copy. In modern JavaScript (ES2023+), you can also use arr.toSorted(), which returns a new sorted array without modifying the original.

Final Thoughts

Comparing arrays correctly takes more than just using == or ===. In JavaScript, use every() or JSON.stringify() for flat arrays, sort copies if you don’t care about order, and write a recursive function for deeply nested structures. In jQuery, you can achieve similar results with $.each() and manual logic.

Join the Discussion
0 Comments  ]

Leave a Comment

To add code, use the buttons below. For instance, click the PHP button to insert PHP code within the shortcode. If you notice any typos, please let us know!

Savvy WordPress Development official logo