2 Simple ways to Compare two Arrays in JavaScript

How to Compare Two Arrays in JavaScript

In this article, we will learn how to compare two arrays in javascript.

What is comparing two arrays?

Comparing two arrays means checking if the elements in both arrays are the same or not. We can compare two arrays in JavaScript using ‘===’ operator, ‘JSON.stringify()’ method, ‘every()’ method, etc. Let’s see this method in detail.

Why should we compare two arrays in javascript?

It is a common task that is often required when working with arrays in programming.

  • If two arrays are equal in order to ensure that they contain the same elements in the same order. This can be useful for validating user input and actual results in testing scenarios.
  • It is also used to find the common elements between two arrays. This can be used to find duplicates or determine the intersection between two sets of data.
  • You may need to sort arrays in order to compare them. Sorting allows you to compare arrays in a consistent and predictable way.

So, if you’re checking for equality, finding common elements, or sorting arrays, being able to compare arrays effectively is an important skill for any JavaScript developer.

2 Best ways to compare two arrays

1. every() method

In this method, we compare two arrays using every() method and it is used to compare each element of both arrays. This method will return true if both arrays have the same elements in any order, and false otherwise.

const arr1 = ['one','two', 'three'];
const arr2 = ['one','two', 'three'];
const arr3 = ['three' ,'two', 'one'];

console.log(arr1.every((el, idx) => el === arr2[idx])); // true
console.log(arr1.every((el, idx) => el === arr3[idx])); // false

2. JSON.stringify()

const arr1 = ['one','two', 'three'];
const arr2 = ['one','two', 'three'];
const arr3 = ['three' ,'two', 'one'];

console.log(JSON.stringify(arr1) === JSON.stringify(arr2)); // true
console.log(JSON.stringify(arr1) === JSON.stringify(arr3)); // false

In this example, JSON.stringify() is used to convert arr1 and arr2 to JSON strings, which are identical. Therefore, the comparison returns true. However, arr1 and arr3 have the same elements, but in a different order, so their JSON strings are not identical and the comparison returns false.

READ ALSO  3 Simple Ways to Return Multiple Values in JavaScript Function


The two methods are comparing arrays with primitive values, they may not be appropriate for comparing complex arrays with nested objects or functions.

Leave a Reply