Altcademy - a Forbes magazine logo Best Coding Bootcamp 2023

How to compare two arrays in JavaScript

In this blog post, we will learn how to compare two arrays in JavaScript. Comparing arrays is a common task when working with data, and JavaScript provides several ways to accomplish this. We will go through different techniques and discuss the pros and cons of each, with examples to help you understand the concepts better. Let's dive in!

Arrays in JavaScript

Before we start comparing arrays, it's essential to understand what an array is in JavaScript. In simple terms, an array is a collection of elements (values) stored in a single variable. These elements can be of any data type, such as numbers, strings, or even other arrays.

Here's an example of an array containing numbers:

let numbers = [3, 5, 7, 9];

And here's an example of an array containing strings:

let fruits = ['apple', 'banana', 'cherry', 'date'];

To access the elements of an array, we use an index, which starts from 0. For example, if we want to access the first element of the numbers array, we would use numbers[0], which would give us the value 3.

Now that we have a basic understanding of arrays in JavaScript, let's learn how to compare them!

Comparing arrays by reference

JavaScript provides a simple way to compare arrays using the === (strict equality) operator. This operator checks whether two variables refer to the same object in memory.

Let's see an example:

let array1 = [1, 2, 3];
let array2 = [1, 2, 3];
let array3 = array1;

console.log(array1 === array2); // false
console.log(array1 === array3); // true

In this example, the === operator returns false when comparing array1 and array2, even though they have the same values. This is because the === operator checks whether the two arrays are the same object in memory, not whether their values are the same.

On the other hand, when comparing array1 and array3, the === operator returns true because both variables refer to the same object in memory.

This method of comparison is not suitable when we want to compare the contents of two arrays because it only checks for reference equality. Let's look at other ways to compare arrays by their content.

Comparing arrays by content

Using a for loop

One of the most basic ways to compare two arrays by their content is by using a for loop to iterate through the elements of the arrays and compare them one by one. Here's an example:

function arraysAreEqual(array1, array2) {
  if (array1.length !== array2.length) {
    return false;
  }

  for (let i = 0; i < array1.length; i++) {
    if (array1[i] !== array2[i]) {
      return false;
    }
  }

  return true;
}

let array1 = [1, 2, 3];
let array2 = [1, 2, 3];
let array3 = [1, 2, 4];

console.log(arraysAreEqual(array1, array2)); // true
console.log(arraysAreEqual(array1, array3)); // false

In this example, we define a function called arraysAreEqual that takes two arrays as arguments. The function first checks whether the arrays have the same length, and if not, it returns false. Then, it uses a for loop to iterate through the elements of the arrays and compare them. If any pair of elements is not equal, the function returns false. If the for loop completes without finding any unequal elements, the function returns true.

This method works well for comparing arrays with primitive values (numbers, strings, booleans), but it might not handle arrays with objects or nested arrays correctly. Let's explore other methods to handle such cases.

Using JSON.stringify

Another way to compare arrays by their content is by converting them to JSON strings using the JSON.stringify method and comparing the resulting strings. This method works well for arrays containing objects or nested arrays, as long as the objects' properties are in the same order.

Here's an example:

function arraysAreEqual(array1, array2) {
  return JSON.stringify(array1) === JSON.stringify(array2);
}

let array1 = [1, 2, {a: 3, b: 4}];
let array2 = [1, 2, {a: 3, b: 4}];
let array3 = [1, 2, {a: 3, b: 5}];

console.log(arraysAreEqual(array1, array2)); // true
console.log(arraysAreEqual(array1, array3)); // false

In this example, the arraysAreEqual function converts the arrays to JSON strings and compares the resulting strings with the === operator. This method can handle arrays containing objects or nested arrays, but it has some limitations. For example, it will not work correctly if the objects' properties are in a different order, even if the values are the same.

Using the .every() method

Another way to compare arrays by their content is by using the .every() method, which is a built-in method of JavaScript arrays. The .every() method checks whether all elements in an array pass a test provided by a callback function.

Here's an example:

function arraysAreEqual(array1, array2) {
  if (array1.length !== array2.length) {
    return false;
  }

  return array1.every((value, index) => value === array2[index]);
}

let array1 = [1, 2, 3];
let array2 = [1, 2, 3];
let array3 = [1, 2, 4];

console.log(arraysAreEqual(array1, array2)); // true
console.log(arraysAreEqual(array1, array3)); // false

In this example, the arraysAreEqual function first checks whether the arrays have the same length, and if not, it returns false. Then, it uses the .every() method with a callback function that compares the current element with the corresponding element in the other array. If all elements pass the test, the .every() method returns true.

This method is more concise than using a for loop, and it works well for arrays with primitive values. However, it might not handle arrays with objects or nested arrays correctly, as it uses the === operator for comparison.

Conclusion

In this blog post, we have learned how to compare two arrays in JavaScript using different methods, such as reference comparison, for loops, JSON.stringify, and the .every() method. Each method has its pros and cons, and the best one depends on the specific use case and the type of data stored in the arrays.

When comparing arrays with primitive values, using a for loop or the .every() method is a great choice. If the arrays contain objects or nested arrays, the JSON.stringify method might be more suitable, but it has some limitations in handling objects with properties in a different order.

Remember to always consider the specific requirements of your project and choose the most appropriate method for comparing arrays in JavaScript. Happy coding!