Articles by FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
FavTutor
  • AI News
  • Data Structures
  • Web Developement
  • AI Code GeneratorNEW
  • Student Help
  • Main Website
No Result
View All Result
Articles by FavTutor
No Result
View All Result
Home Web Developement

Compare Two Arrays in JavaScript (5 Methods)

Nikita Arora by Nikita Arora
February 20, 2024
Reading Time: 6 mins read
Compare Two Arrays in JavaScript
Follow us on Google News   Subscribe to our newsletter

When working with JavaScript, we often come across situations where we need to compare two arrays to check if they are equal or not. In this article, we will cover various methods to compare two arrays in JavaScript using conversion to strings, looping through array elements, and using external libraries.

5 Ways to Compare Two Arrays in JavaScript

We can compare any two values in JavaScript by “==” and “===”, but this is not applicable here because the datatype of an array is an object, and when comparing objects the equality operators check for reference equality rather than value equality.

Let’s explore methods to compare two arrays. It’s important to note that each method may have some drawbacks, therefore we have to choose the best method according to our use case.

1) JSON.stringify()

The simplest way to compare two arrays in JavaScript is by converting an array into a JSON string, making them ready for comparison directly. 

For example:

// Declare three arrays
let arr1 = [1,2,4,5];
let arr2 = [1,2,3,4];
let arr3 = [1,2,4,5];

// Comparing using stringify method

console.log(JSON.stringify(arr1) === JSON.stringify(arr2));

console.log(JSON.stringify(arr1) === JSON.stringify(arr3));

Output:

false
true

We can successfully compare two arrays with this method. However, some points to keep in mind are:

As this method converts JavaScript objects(including arrays) to JSON-formatted strings, therefore null and undefined both are represented as null. We should avoid this method if we want to treat null and undefined distinctly.

This method works well for basic data types like strings, numbers, and objects. However, it does not support custom objects with methods like Map, Set, or arrays that contain functions.

2) Using .toString()

The .toString() method converts any data types, including objects to a string representation which can then be compared directly.

// Declare three arrays
let arr1 = [1,2,4,5];
let arr2 = [1,2,3,4];
let arr3 = [1,2,4,5];

// Comparing using .toString method

console.log(arr1.toString() === arr2.toString());

console.log(arr1.toString() === arr3.toString());

Output:

false
true

However JSON.stringify() is preferred over .toString() because of following reasons:

`JSON.stringify` preserves the structure of the array. It serializes the array into a string without altering its original shape. This is important when dealing with nested arrays or arrays of objects.

When an array contains nested arrays or objects, `JSON.stringify` recursively serializes, whereas .toString() simply converts the array to a comma-separated string, which leads to loss of hierarchical information. For example:

// Original array with different data types and nested structures
let array = [1, [2, 3], { key: 'value' }];

// using .toString() method on the array
console.log(array.toString());

// using JSON.stringify() method on the array
console.log(JSON.stringify(array));

Output:

"1,2,3,[object Object]"
"[1,[2,3],{"key":"value"}]"

Therefore `JSON.stringify` provides a more accurate and complete representation of the array, including nested arrays and objects.

3) Using every()

This is an example of looping over the array, we can compare each element of an array to the corresponding element in the other array. In the every() method, a callback function is executed for each element in an array, which receives the current element, its index, and the array as parameters.

We will first check the length of both arrays because if the length is not the same, then no need to check the whole array. Here is an example:

// Function to compare two arrays element-wise
const comparison = (arrayA, arrayB) => {
  // Check if the lengths of the arrays are equal
  // and if every corresponding value in the arrays is identical
  return (
    arrayA.length === arrayB.length &&
    arrayA.every((value, index) => value === arrayB[index])
  );
};

// Example arrays for testing the comparison function
let array1 = [1, 2, 3, null];
let array2 = [2, 2, 3, 4];
let array3 = [1, 2, 3, undefined];

// Testing the comparison function with example arrays
console.log(comparison(array1, array2));
console.log(comparison(array1, array3));

Output:

false
false

4) Using a for Loop

This method involves manually iterating over each element of the arrays and comparing them one by one. It uses a for loop in combination with if statements. This is an easy method for beginners and provides more control over the comparison process.

function comparison(array1, array2) {
  // Check if the arrays have the same length
  if (array1.length !== array2.length) {
    return false;
  }

  // Iterate through the elements of the arrays
  for (let i = 0; i < array1.length; i++) {
    // Compare the current elements
    if (array1[i] !== array2[i]) {
      return false;
    }
  }

  // If the loop completes without returning false, the arrays are equal
  return true;
}

// Example arrays for testing the comparison function
let Array1 = [1, 2, 3, null];
let Array2 = [1, 2, 3, 4];
let Array3 = [1, 2, 3, Undefined];
let Array4 = [1, 2, 3, 4];


// Testing the comparison function with example arrays
console.log(comparison(Array1, Array2));
console.log(comparison(Array1, Array3));
console.log(comparison(Array2, Array4));

Output:

false
false
true

Here after comparing lengths, we compared each element at the corresponding index. If any pair of elements is not equal, the function returns false. If all the elements pass the comparison, true is returned.

But we have to keep in mind for comparing more complex scenarios, especially involving nested arrays or objects, we may need to implement additional custom logic.

5) Using Lodash _.isEqual()

If you prefer using external libraries, Lodash provides a convenient method known as isEqual() to compare two arrays. We first need to import the _.isEqual() library.

The Lodash _.isEqual() method performs a deep comparison, which is beneficial when we are comparing arrays in a more complex scenario such as when the arrays contain objects or nested arrays.

// Importing isEqual method from lodash
const  _ = require('lodash');

// Example arrays
const Array1 = [1, 2, 3];
const Array2 = [1, 2, 3];
const array3 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }];
const array4 = [{ id: 1, name: 'Alice' }, { id: 2, name: 'Charlie' }];

//Checking for equal values
console.log(_.isEqual(Array1,Array2));
console.log(_.isEqual(Array3,Array4));

Output:

true
false

This method can be a convenient and reliable way to compare arrays, especially in cases when we have complex data structures.

Conclusion

We have successfully covered various methods to compare two arrays in JavaScript, with their advantages and limitations. Therefore which method to opt for will depend on the use case. Now you can learn to Sort an Array of Objects in JavaScript.

ShareTweetShareSendSend
Nikita Arora

Nikita Arora

I'm Nikita, a B.Tech Computer Engineering student. My passion lies in web development, data structures, and algorithms. Committed to continuous learning, I find immense joy in sharing insights and fostering collaboration among like-minded peers in web development. Excited about exploring interesting opportunities in technology.

RelatedPosts

Javascript Animation Libraries

Top 10 JavaScript Animation Libraries in 2025

February 19, 2025
JavaScript Interview Questions

Top 40 JavaScript Interview Questions and Answers in 2024

April 1, 2025
Best React UI Component Libraries

10 Must-Know React UI Component Libraries for Web Devs 2024

May 7, 2024
Currying in JavaScript

Currying in JavaScript Explained (with Examples)

March 15, 2024
Javascript Format Currency

Javascript Program for Format Currency

April 8, 2025

About FavTutor

FavTutor is a trusted online tutoring service to connects students with expert tutors to provide guidance on Computer Science subjects like Java, Python, C, C++, SQL, Data Science, Statistics, etc.

Categories

  • AI News, Research & Latest Updates
  • Trending
  • Data Structures
  • Web Developement
  • Data Science

Important Subjects

  • Python Assignment Help
  • C++ Help
  • R Programming Help
  • Java Homework Help
  • Programming Help

Resources

  • About Us
  • Contact Us
  • Editorial Policy
  • Privacy Policy
  • Terms and Conditions

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.

No Result
View All Result
  • AI News
  • Data Structures
  • Web Developement
  • AI Code Generator
  • Student Help
  • Main Website

Website listed on Ecomswap. © Copyright 2025 All Rights Reserved.