Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk4 min

How to Check Array Equality in TypeScript

TypeScript arrays use JavaScript’s reference equality. Compare lengths and matching indexes for ordered primitive values, and define explicit rules for objects, duplicates, and nested data.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

In TypeScript, a === b checks whether two variables refer to the same array—not whether their elements match. To compare ordered arrays of primitive values, check that their lengths match and then compare each pair of values at the same index. For objects, nested arrays, or order-independent comparisons, first decide what “equal” means for your data.

Choose the equality rule you need

JavaScript’s runtime equality rules apply to arrays in TypeScript. Type annotations do not change how equality works when the code runs. TypeScript’s 4.8 release notes explain that arrays and other objects are compared by reference with ===.

What you mean by equal Approach Important distinction
Same array instance a === b Separately created arrays are different references, even if their contents match.
Same ordered primitive values Equal lengths, then compare each index Choose how special values such as NaN should compare.
Same ordered objects by identity Equal lengths, then compare references at each index Matching fields do not make separate objects equal.
Same ordered object structure A domain-specific comparator or deep-equality utility Define how nested values and special object types should be treated.
Same values regardless of order A set or multiset comparison suited to the element type A set ignores duplicate counts; a multiset preserves them.

Compare ordered arrays of primitive values

For numbers, strings, booleans, or other values whose intended comparison is ===, compare lengths before checking corresponding elements:

function arraysEqual<T>(a: readonly T[], b: readonly T[]): boolean {
  return a.length === b.length && a.every((value, index) => value === b[index]);
}

arraysEqual([1, 2, 3], [1, 2, 3]); // true
arraysEqual([1, 2], [2, 1]);       // false

The length check is necessary because every() returns true for an empty array: there are no elements that fail the test. Without the check, an empty first array could appear to match a non-empty second array. MDN documents this behavior, along with how every() handles sparse arrays, in its reference for Array.prototype.every().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Decide how to compare NaN

With the comparator above, NaN does not match itself because NaN === NaN is false. If your equality rule should treat NaN as equal to itself, use Object.is as the element comparison:

function arraysEqualIncludingNaN<T>(a: readonly T[], b: readonly T[]): boolean {
  return a.length === b.length && a.every((value, index) => Object.is(value, b[index]));
}

Object.is and === also differ in how they treat positive and negative zero. MDN’s guide to equality comparisons and sameness explains these distinctions. Select the rule that matches your application rather than treating one comparator as universally correct.

Rank #2
TypeScript Programming Language - Software Engineer & Coder T-Shirt
  • TypeScript implements a superset of syntax for strictly typed development, facilitating deep static analysis and enhanced development environment integration. The compiler translates source into standard script formats, ensuring parity across any runtime.
  • TypeScript is ideal for front-end developers, full-stack engineers, and software architects who build large-scale web applications. It serves those looking to improve code excellence, reduce bugs through static checking, and maintain complex projects more.
  • Lightweight, Classic fit, Double-needle sleeve and bottom hem

Compare arrays containing objects or nested arrays

The element-by-element function compares each element with ===. For object elements, that means reference identity, not matching fields. Two separately created objects such as { id: 1 } are unequal under ===, even though their visible properties match. The same applies to nested arrays.

Compare by a domain key when that defines equality

If two records count as equal when they have the same identifier, compare that identifier explicitly:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
type Item = { id: number; name: string };

function itemsEqualById(a: readonly Item[], b: readonly Item[]): boolean {
  return a.length === b.length && a.every((item, index) => item.id === b[index].id);
}

This deliberately ignores fields other than id. If those other fields matter, include them in the rule instead of assuming key equality means full structural equality.

Use deep comparison only with defined semantics

There is no universal built-in deep-equality operator in JavaScript. A recursive comparator or library may make different choices about dates, maps, sets, cycles, prototypes, and special values. MDN’s comparison guide notes that deep comparison behavior depends on the implementation. Choose a comparator whose documented rules match your data.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Compare values without regard to order

First decide whether duplicate counts matter. If these arrays should be equal, a set-style comparison can work because order is irrelevant and duplicates are intentionally discarded:

new Set(["a", "b", "b"]).size === new Set(["b", "a"]).size

That expression compares only the number of distinct values, not membership, so it is not by itself a complete equality check. A proper set comparison must check membership in both directions. If duplicates matter, compare multiplicities as well: ["a", "b", "b"] is not equivalent to ["a", "a", "b"] under multiset equality.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Sorting both inputs before comparing can be appropriate only when there is a meaningful ordering for the element type. Sorting also mutates arrays unless you work on copies. For objects, define the key or comparator used for ordering and equality; a generic sort does not supply those semantics.

Handle sparse arrays and serialization deliberately

Sparse slots are not the same as ordinary values

every() skips empty slots in sparse arrays rather than calling the callback for them. As a result, a comparison based on every() may not distinguish a hole from an explicit undefined the way your application expects. If sparse arrays are possible, decide whether holes and undefined should count as different, then use a comparison that checks slot presence as well as value.

JSON stringification is not general deep equality

Comparing JSON.stringify(a) and JSON.stringify(b) is only a shortcut when the data is known to be JSON-serializable and the serialized representation is the intended rule. Serialization can erase or transform distinctions, so it should not stand in for a general structural comparison.

Common mistakes to avoid

  • Using === for matching contents: it answers whether the references are identical, not whether elements match.
  • Skipping the length check: an empty left array passes every() because its callback is never invoked.
  • Assuming shallow comparison is deep comparison: object elements and nested arrays are still compared by reference.
  • Using a set when duplicates matter: sets discard duplicate occurrences.
  • Sorting the originals unintentionally: sorting mutates arrays, and an ordering may not exist for the values being compared.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Crashes, No Sound, or Screen Glitches?Free driver scan
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.