How to Check Array Equality in TypeScript?

As a developer, you might encounter scenarios where you need to verify the equality of arrays, such as comparing user preferences, validating data integrity, or optimizing performance. In this tutorial, I will explain how to check if two arrays are equal using TypeScript.

Understanding Array Equality in TypeScript

First, Let me explain what we mean by “array equality.” Two arrays are considered equal if they have the same length and contain the same elements in the same order. For example, consider the following arrays:

const employeeIds1 = [1001, 1002, 1003];
const employeeIds2 = [1001, 1002, 1003];

In this case, employeeIds1 and employeeIds2 are equal because they have the same elements in the same order.

However, if the arrays have the same elements but in a different order, they are not considered equal:

const employeeIds3 = [1003, 1001, 1002];

Here, employeeIds1 and employeeIds3 are not equal, even though they contain the same elements.

Check out How to Check if a Value Exists in an Array in TypeScript?

Compare Arrays Using the Equality Operator (===)

One common misconception is that you can compare arrays using the equality operator (===) in TypeScript. However, this operator compares the references of the arrays rather than their contents. Equality operators ( == or === ) both work differently for objects (Type of array is an object in JS ) when compared to other primitive types.

const employeeNames1 = ['John', 'Emily', 'Michael'];
const employeeNames2 = ['John', 'Emily', 'Michael'];

console.log(employeeNames1 === employeeNames2); // Output: false

Even though employeeNames1 and employeeNames2 have the same elements, the equality operator returns false because they are two different array objects in memory.

Here is the exact output in the screenshot below:

Array Equality in TypeScript

Method 1: Using JSON.stringify()

One simple approach to compare arrays in TypeScript is by using the JSON.stringify() method. This method converts the arrays to JSON strings, which can then be compared using the equality operator.

const states1 = ['California', 'Texas', 'Florida'];
const states2 = ['California', 'Texas', 'Florida'];

console.log(JSON.stringify(states1) === JSON.stringify(states2)); // Output: true

While this method works for simple arrays, it has limitations. It doesn’t work well with arrays containing objects, as the order of object properties might affect the JSON string representation.

Read Concatenate Arrays in TypeScript Using concat()

Method 2: Using Array.prototype.every()

A more robust approach is to use the Array.prototype.every() method along with the Array.prototype.includes() method. This combination allows you to compare arrays element by element.

function arraysEqual(arr1: any[], arr2: any[]): boolean {
  if (arr1.length !== arr2.length) {
    return false;
  }
  return arr1.every((element) => arr2.includes(element));
}

const cities1 = ['New York', 'Los Angeles', 'Chicago'];
const cities2 = ['New York', 'Los Angeles', 'Chicago'];
const cities3 = ['Chicago', 'New York', 'Los Angeles'];

console.log(arraysEqual(cities1, cities2)); // Output: true
console.log(arraysEqual(cities1, cities3)); // Output: true

The arraysEqual function first checks if the arrays have the same length. If not, it returns false. Then, it uses every() to iterate over each element of arr1 and checks if it is included in arr2 using includes(). If all elements are found, the function returns true, indicating that the arrays are equal.

However, this method has a time complexity of O(n^2) because it performs a nested loop to compare each element. For large arrays, this can be inefficient.

Here is the exact output in the screenshot below:

Check Array Equality in TypeScript

Read Find an Object in an Array by Property in TypeScript

Method 3: Using a Set

A more efficient approach is to use a Set to compare arrays. A Set is a built-in object in TypeScript that stores unique values. By converting the arrays to sets and comparing their sizes, we can determine if the arrays are equal.

function arraysEqual(arr1: any[], arr2: any[]): boolean {
  const set1 = new Set(arr1);
  const set2 = new Set(arr2);

  if (set1.size !== set2.size) {
    return false;
  }

  for (const item of set1) {
    if (!set2.has(item)) {
      return false;
    }
  }

  return true;
}

const products1 = ['iPhone', 'iPad', 'MacBook'];
const products2 = ['iPhone', 'iPad', 'MacBook'];
const products3 = ['iPhone', 'iPad', 'MacBook', 'AirPods'];

console.log(arraysEqual(products1, products2)); // Output: true
console.log(arraysEqual(products1, products3)); // Output: false

This approach has a time complexity of O(n) because it iterates over the elements only once. It is more efficient than the previous methods, especially for large arrays.

Read Convert a Map to an Array in TypeScript

Comparing Arrays of Objects

When comparing arrays of objects, the equality comparison becomes more complex. Two objects are considered equal only if they reference the same object in memory. To compare arrays of objects, you need to compare the individual properties of each object.

interface Employee {
  id: number;
  name: string;
}

function employeeArraysEqual(arr1: Employee[], arr2: Employee[]): boolean {
  if (arr1.length !== arr2.length) {
    return false;
  }

  return arr1.every((employee, index) =>
    employee.id === arr2[index].id && employee.name === arr2[index].name
  );
}

const employees1: Employee[] = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Emily' },
];

const employees2: Employee[] = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Emily' },
];

const employees3: Employee[] = [
  { id: 2, name: 'Emily' },
  { id: 1, name: 'John' },
];

console.log(employeeArraysEqual(employees1, employees2)); // Output: true
console.log(employeeArraysEqual(employees1, employees3)); // Output: false

In this example, the employeeArraysEqual function compares arrays of Employee objects. It checks the id and name properties of each object at the corresponding index using every().

Conclusion

In this tutorial, I explained how to check array equality in TypeScript using various methods. For simple arrays, using JSON.stringify() or Array.prototype.every() with Array.prototype.includes() can suffice. However, for better performance, especially with large arrays, using a Set is more efficient.

When dealing with arrays of objects, you need to compare the individual properties of each object to determine equality.

You may also like:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.