Comparing Two Arrays in JavaScript

Comparing Two Arrays in JavaScript

Comparing two arrays in JavaScript looks easy, but it is not as easy as you think. It becomes difficult due to the JavaScript nature of handling objects and references. Besides the primitive data types (like numbers or strings), arrays are the reference data types in JavaScript, which means that if two arrays have the same elements but have different references or memory locations, they are not considered to be equal. There are multiple techniques available for JavaScript array comparison depending on the structure and order of the arrays involved.

In this blog, you will explore different methods to compare the arrays in JavaScript, their advantages, and best practices to know the best way to compare two arrays in JavaScript.

Table of Contents:

Method to Compare Two Arrays in JavaScript

JavaScript provides various methods to compare two arrays. In this section, we will show you how to check if arrays are equal in JavaScript using different built-in and library-based approaches.

Method 1: Use JSON.stringify() for Quick Array Comparison

It is one of the simplest ways to compare arrays in JavaScript. You can first convert them into JSON strings and check whether the resulting strings are equal or not. It returns an answer in the form of true or false.

Example:

Javascript

Output:

Use JSON.stringify() for Quick Array Comparison

Explanation: In this example, you are using JSON.stringify() for comparing arrays. It has a simple and more readable syntax.

From HTML to full-stack development, learn everything you need to succeed.
Master Web Development – Join Our Course!
quiz-icon

Method 2: Compare Arrays Using a for Loop

The for loop is a more traditional method for comparing two arrays. It involves checking each element one by one from both arrays.

Example:

Javascript

Output:

Compare Arrays Using a for Loop

Explanation: In this example, a traditional for loop is used to compare the two arrays. First, it checks for the length of both arrays; if they are not equal, then it returns “Not Equal”. But if they are equal, then the for loop iterates over each element of the array and compares every element.

Method 3: Convert and Compare Arrays Using join()

The join() method converts an array to a string, and after doing this conversion, we can do a simple comparison between the two strings.

Example:

Javascript

Output:

Convert and Compare Arrays Using join()

Explanation: The join() method also converts an array into a string and then checks for the equality of both strings. If it is found equal, then return true. Otherwise, return false.

Method 4: Use every() to Check Element-wise Equality

This method checks that every element of one array matches the corresponding elements of the second array.

Example:

Javascript

Output:

Use every() to Check Element-wise Equality

Explanation: In this example, the Array.prototype.every() method checks each element in the array using its index (idx) and prints the output in the form of true or false.

Method 5: Deep Compare Arrays using Lodash isEqual()

You can compare arrays using lodash isEqual. For comparing nested arrays (deep comparison), the .isEqual() method from the Lodash library is used.

Example:

Javascript

Output:

Deep Compare Arrays using Lodash isEqual()

Explanation: An External library like Lodash, which is used for comparing arrays in JavaScript. If arrays contain nested arrays, then using the .isEqual() method of the Lodash library is the best choice. For scenarios involving nested arrays in JavaScript, comparing arrays with nested values can be effectively handled using Lodash’s deep comparison utility.

Method 6: Compare Arrays Without Order Using Set

If the order of elements doesn’t matter, you can compare unordered arrays in JavaScript using sets or sorting techniques. An unordered comparison means comparing the elements without thinking about the order in which the elements are compared, and a Set allows you to compare arrays without considering element order.

Example:

Javascript

Output:

Compare Arrays Without Order Using Set

Explanation: In this example, the Set method is used to convert an array into a set, then, after converting it into a set, JavaScript performs the comparison.

Method 7: Sort and Compare Arrays (Unordered Check)

To check if two arrays are the same without order, you can use a Set-based comparison or sort both arrays before comparing them. Sorting both arrays before comparing them is another method for comparing arrays in JavaScript, but this is difficult and least recommended because you need to write extra code for sorting the arrays.

Example:

Javascript

Output:

Sort and Compare Arrays (Unordered Check)

Explanation: In this example, the arr.slice().sort() is used for sorting the array, then .join() method is used for converting it into a string and performing comparison.

Performance & Use Case Comparison of Each Method

Here is the performance comparison between all the methods used for comparing two objects in JavaScript:

Method Best For Advantages Limitations Time Complexity
JSON.stringify() Simple Arrays Easy to implement and works well for 1D arrays. Fails for nested structures. O(n)
for Loop Small and ordered Arrays Better than JSON.stringify() Not good for deep comparison. O(n)
join() Performing quick checks. Quick and easy Doesn’t handle complex data. O(n)
every() Simple equality checks. More concise than using a loop. Fails for nested arrays. O(n)
isEqual() Best for deep comparison Handles deep comparison(Nested arrays) well. Requires external library “Lodash” O(n) – O(n2)
Set Unordered Comparison (the order of elements does not matter while comparing) Works well for unordered arrays. Does not handle duplicate elements. O(n)
Sorting + Comparison Unordered Comparison This also works well for unordered arrays. Need to write extra code for sorting arrays. O(n logn)

Practical Use Cases of Array Comparison in JavaScript

  • Validating User Input: Comparing two arrays in JavaScript is helpful in comparing user-selected options with stored choices.
  • API Response Comparison: Checking the output responses of the APIs helps in making the comparison.
  • Shopping Cart Updates: Used for detecting changes in cart items.

Get 100% Hike!

Master Most in Demand Skills Now!

Conclusion

To compare two arrays for equality in JavaScript, you can choose from several methods based on your use case. For simple or shallow checks, use JSON.stringify() or join(). For deep comparison, especially when arrays contain nested values, use Lodash’s isEqual(). If you need to compare arrays without considering order, sorting, or Set-based techniques are effective. These JavaScript array comparison methods help ensure accurate and efficient results.

Comparing Two Arrays in JavaScript – FAQs

Q1. How do you compare arrays in JavaScript unordered?

Sort both arrays using .sort() and then compare them with JSON.stringify(arr1) === JSON.stringify(arr2), or use .every() with .includes() for element-wise checking.

Q2. How to compare two arrays for equality in JavaScript?

To compare two arrays for equality in JavaScript, check their lengths first, then compare each element using arr1.every((val, idx) => val === arr2[idx]). For unordered arrays, sort them before comparison or use JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort()).

Q3. What does the !== mean in JavaScript?

The !== is the “not equal” operator, which is used to check whether the two values are equal or not, based on the value and type.

Q4. How do you compare the values of two objects?

Objects are reference types in JavaScript; to compare the values of two objects, you need to compare their keys and values. For comparing the values of two objects, you can use JSON.stringify or the lodash library.

Q5. What is ${} in JavaScript?

${} is used inside template literals (backticks ` `) for writing embedded expressions in strings. Syntax: let name = "Intellipaat"; console.log(`Hello, ${name}!`);

Q6. How to check if arrays are equal in JavaScript?

Use arr1.every((val, idx) => val === arr2[idx]) for ordered comparison, or sort both arrays before comparing them with JSON.stringify(arr1) === JSON.stringify(arr2).

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner