How to Check if Two Arrays are Equal in JavaScript

How to Check if Two Arrays are Equal in JavaScript | This article aims to compare two arrays, and we must ensure that both arrays are the same length, that the objects included in both are of the same type, and that each item in one array is equivalent to its counterpart in the other array. By doing this, we can determine whether or not the two arrays are identical. Also see:- How To Limit Size of an Array In JavaScript

Check if Two Arrays are Equal in JavaScript Using JSON

To turn an object or array into a JSON string, JavaScript has the function JSON.stringify() method. We can quickly determine whether two strings are equal by transforming them into JSON strings.

In this example, an object or array is converted into a JSON string using the JSON.stringify() function, and the condition is then checked. It yields true if the specific situation is met; else, it returns false.

var a = [1, 2, 3];
var b = [1, 2, 3];

// Comparing both arrays using stringify
if (JSON.stringify(a) == JSON.stringify(b)) {
  console.log(true);
} else {
  console.log(false);
}

var f = [1, 2, 4];
if (JSON.stringify(a) == JSON.stringify(f)) {
  console.log(true);
} else {
  console.log(false);
}

Output:-

true
false

Check if Two Arrays are Equal in JavaScript Manually

In this example, every item is manually checked to see whether they are equal. If not, a false response is returned.

function isEqual(a, b) {
  // If length is not equal
  if (a.length != b.length) {
    return false;
  } else {
    // Comparing each element of the array
    for (var i = 0; i < a.length; i++) {
      if (a[i] != b[i]) {
        return false;
      }
    }
    return true;
  }
}

var a = [1, 2, 3];
var b = [1, 2, 3];
var bool = isEqual(a, b);
console.log("Arrays a & b are equal?:", bool);

var c = [1, 2, 4];
bool = isEqual(a, c);
console.log("Arrays a & c are equal?:", bool);

Output:-

Arrays a & b are equal?: true
Arrays a & c are equal?: false

Using the above two ways you can check if two arrays are equal in JavaScript or not. The JSON.stringify() method converts the array to JSON string so it could be an easy way to compare two arrays.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *