This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
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.
The post How to Check For Array Equality in Javascript appeared first on CodeSource.io.
This content originally appeared on CodeSource.io and was authored by Ariessa Norramli
Ariessa Norramli | Sciencx (2021-03-06T13:26:09+00:00) How to Check For Array Equality in Javascript. Retrieved from https://www.scien.cx/2021/03/06/how-to-check-for-array-equality-in-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.