javascript

How to Check For Array Equality in Javascript


In this article, you will learn how to check for array equality in Javascript.

Let’s say you have 3 arrays.

var a = [1, 2, 3];
var b = [1, 2, 3];
var c = [5, 6, 7];

Check For Array Equality

In order to check for array equality, you can use the Array.length property and Array.every() method.

var a = [1, 2, 3];
var b = [1, 2, 3];
var c = [5, 6, 7];
  
// Check if every element in firstArray is strictly equals to the corresponding
// element in secondArray
function checkEveryElement(a, b) {
	return a.every((v, i) => v === b[i]);
}

// Check if both arrays have equal length and every element is strictly equal
// in both arrays
function arrayEquality(a, b) {
	if (a.length === b.length && checkEveryElement(a, b)) {
  	console.log("[" + a + "] and [" + b + "] are equal");
  }
  
  else {
  	console.log("[" + a + "] and [" + b + "] are not equal");
  }
}

arrayEquality(a, b);
// => "[1,2,3] and [1,2,3] are equal"

arrayEquality(b, c);
// => "[1,2,3] and [5,6,7] are not equal"

Note: The Array.length property functions by returning the length of the array. The Array.every() method functions by executing a function on every array element.


Share on social media

//