Table of contents
1.
Introduction
2.
Methods to Compare Two Arrays in JavaScript
2.1.
Equality Comparison
2.2.
Compare Arrays Using JSON.stringify()
2.3.
Compare Arrays Using .tostringify()
2.4.
Compare Arrays Using For Loop
2.5.
Using Array.prototype.every()
2.6.
Using Array.prototype.every() With Recursion
2.7.
Using Set And Array.Prototype.Filter() In Combination With A Loop
3.
Limitation of .Stringify and Way Forward
4.
Frequently Asked Questions
4.1.
How to compare two arrays in javascript?
4.2.
How to check if two arrays match JavaScript?
4.3.
How to deep compare two arrays in JavaScript?
4.4.
How to compare two array of string in JavaScript?
5.
Conclusion
Last Updated: Mar 27, 2024
Easy

Compare Two Arrays in JavaScript

Compare Two Arrays in JavaScript

Introduction

JavaScript is best known for web page development but is also used in various non-browser environments. While working on JavaScript, the most common thing you deal with is “logic.” When handling logic in the backend, we might need to compare two arrays to see if they are equal or not.

This article will discuss how to compare two arrays in JavaScript in the right way. We will go through every aspect and boundary condition too. We will use two approaches to do so. We will do it by converting arrays to strings and comparing two arrays by looping through their values.

So without any further ado. Let’s get started! 

See, Javascript hasOwnProperty

Methods to Compare Two Arrays in JavaScript

Let’s have a look at some of the methods to compare two arrays in Javascript.

Equality Comparison

How to compare two arrays in Javascript? The first thing that comes to our mind when this question shows up is, “We can use strict or loose equality operator to do this.” Well, it’s not wrong, but do you know we can’t use them here? 

Well, if you use either the loose or strict equality operators (== or ===), it will most often result in a wrong (false) answer. Even if the two arrays have the same elements in the same order. 

const array1 = [1, 2, 3, 4];
const array2 = [1, 2, 3, 4];

array1 === array2; // false

 

This is because the arrays and objects are compared by reference and not by value in JavaScript. This means this solution does not produce the desired result:

let arrayType = typeof(array1);
console.log(arrayType); //"Object"

 

Then how to compare two arrays in JavaScript? 

Compare Arrays Using JSON.stringify()

A standard answer to the question of how to compare two arrays in JavaScript is to use JSON.stringify(). This will allow us to serialize each array, and then we can compare the two serialized strings.

A simple implementation of this is shown below:

const equals = (array1, array2) => JSON.stringify(array1) === JSON.stringify(array2);

const array1 = [1, 2, 3, 4];
const array2 = [1, 2, 3, 4];

equals(array1, array2); // true

Compare Arrays Using .tostringify()

Another approach to the problem of how to compare two arrays in JavaScript is to use .toString(). As we had discussed in JSON.stringify(), this method will convert any data type to a string. And we can similarly convert an object to a string.

const array1 = [1, 2, 3, 4];
const array2 = [1, 2, 3, 4];

console.log(array1.toString() === array2.toString()); //true

Compare Arrays Using For Loop

In this method we'll compare each and every element of both the array one by one.

function compareArrays(arrfirst, arrsecond) {
 if (arrfirst.length !== arrsecond.length) {
   return false;
 }
 
 for (let i = 0; i < arrfirst.length; i++) {
   if (arrfirst[i] !== arrsecond[i]) {
     return false;
   }
 }
 
 return true;
}
const array1 = [3, 4, 8];
const array2 = [1, 2, 3];
const array3 = [3, 4, 8];
console.log(compareArrays(array1, array2)); 
console.log(compareArrays(array1, array3)); 

Output

false
true

Using Array.prototype.every()

In Array.prototype.every() method to compare two arrays in JavaScript. The every() method tests whether all elements in the array pass the test implemented by the provided function.

Example:

function compareArrays(arrfirst, arrsecond) {
 if (arrfirst.length !== arrsecond.length) {
   return false;
 }
 return arrfirst.every((value, index) => value === arrsecond[index]);
}
const array1 = [3, 4, 8];
const array2 = [1, 2, 3];
const array3 = [3, 4, 8];
console.log(compareArrays(array1, array2)); 
console.log(compareArrays(array1, array3)); 

Output:

false
true

Using Array.prototype.every() With Recursion

In this Array.prototype.every() With Recursion, whenever we find a nested object in the arrays, we will recursively call this function for those objects and then proceed.

Example:

function compareArrays(arrfirst, arrsecond) {
 if (arrfirst.length !== arrsecond.length) {
   return false;
 }
 return arrfirst.every((value, index) => {
   if (Array.isArray(value) && Array.isArray(arrsecond[index])) {
     return compareArrays(value, arrsecond[index]);
   } else {
     return value === arrsecond[index];
   }
 });
}
const array1 = [1, [2, 3], 4];
const array2 = [1, [2, 3], 4];
const array3 = [1, [2, 3, 4], 5];
console.log(compareArrays(array1, array2)); 
console.log(compareArrays(array1, array3)); 

Output:

true
false

Using Set And Array.Prototype.Filter() In Combination With A Loop

You can use a combination of Set and Array.prototype.filter() with a loop to compare two arrays in JavaScript. 

Example: 

function compareArrays(arrfirst, arrsecond) {
 if (arrfirst.length !== arrsecond.length) {
   return false;
 }
 const set1 = new Set(arrfirst);
 const filteredArr2 = arrsecond.filter((value) => set1.has(value));
 return arrfirst.length === filteredArr2.length;
}
const array1 = [3, 4, 8];
const array2 = [1, 2, 3];
const array3 = [3, 4, 8];
console.log(compareArrays(array1, array2));
console.log(compareArrays(array1, array3)); 

Output: 

false
true

Limitation of .Stringify and Way Forward

Limitation of .Stringify and Way Forward

While using .Stringify seems like a short, great and easy solution. It falls short on some edge cases. For example:

const string = 'a';
const stringObj = new String('a');
string === stringObj; // false
equals([string], [stringObj]); // true, but it should be false

null === undefined; // false
equals([null], [undefined]); // true, but it should be false

 

While it is uncommon to find these cases. They might cause some very annoying issues, which can be hard to track down and fix. This is why this solution is not recommended for most use cases.

Must Read Fibonacci Series in JavaScript

Frequently Asked Questions

How to compare two arrays in javascript?

There are several methods to compare two arrays in javascript which are Equality Comparison, comparison using JSON.stringify(), comparison using For Loop, comparison Array.prototype.every(), and comparison using Array.prototype.every() With Recursion.

How to check if two arrays match JavaScript?

The function Array.prototype.every() can be used to check if two arrays match javascript, in which each element of the arrays are compared, and if the match is found, it returns true and false if not matched.

How to deep compare two arrays in JavaScript?

To deep compare two arrays in JavaScript, you can use JSON.stringify() method to convert each array into a JSON string and then compare the resulting strings for equality, which will compare their contents and structure.

How to compare two array of string in JavaScript?

In JavaScript, you can iterate over each element (or string) of the array and compare each string at the corresponding index. The comparison can be made using the === operator to determine if they are of the same length.

Conclusion

This article briefly discussed how to compare two arrays in JavaScript. We discussed various methods for it such as converting arrays to strings and comparing two arrays by looping through their values.  We also talked about some limitations and an ordered approach thus concluding our discussion on the topic of how to compare two arrays in Javascript.

We hope that this blog has helped you enhance your knowledge about the topic of how to compare two arrays in JavaScript. If you like to learn more, you can check out our articles: 

Recommended problems -

 

Refer to our Guided Path on Coding Ninjas Studio to upskill yourself in Data Structures and AlgorithmsCompetitive ProgrammingJavaScript, and many more! If you wish to test your competency in coding, you may check out the mock test series and participate in the contests hosted on Coding Ninjas Studio! 

If you have just started your learning process and are looking for questions asked by tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

Nevertheless, you may consider our paid courses to give your career an edge over others!

Do upvote our blogs if you find them helpful and engaging!

Happy Learning!

Live masterclass