In this article we will learn how to compare two arrays in JavaScript.
It is very common to compare two arrays in JavaScript in JavaScript.
Problem
Now we have a problem which is that we want to compare two arrays.
And we will create a function, if the two arrays are equals, it returns true
, and if they are not, it returns false
.
Imagine we have two arrays like this:
const array1 = [1, 2, 3, 4];
const array2 = [1, 2, 3, 4, 5];
Are they equals? The answer is no, so the result will be false
false
How to make a function that solves this problem?
The solution to this problem is easy, and fortunately there is already a built-in function that we can use to solve this problem, which is every
.
Compare two arrays using every
method
We can use every
method to compare two arrays.
Let's see an example
function areEquals(array1, array2) {
if (array1.length === array2.length) {
return array1.every((value, index) => array2[index] == array1[index]);
}
return false;
}
console.log(areEquals([1, 2, 3, 4], [1, 2, 3, 4, 5]));
console.log(areEquals([1, 2, 3, 4], [1, 2, 3, 4]));
Output
false
true
The every() method tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value. MDN
Compare two arrays using JSON.stringify()
We can use JSON,stringify()
to convert array to a string and compare it.
Let's see an example
// Arrays
const array1 = [1, 2, 3, 4];
const array2 = [1, 2, 3, 4, 5];
const array3 = [1, 2, 3, 4];
// Compare
JSON.stringify(array1) == JSON.stringify(array2);
JSON.stringify(array1) == JSON.stringify(array3);
Output
false
true
Thank you for reading
Thank you for reading my blog. 🚀