How to compare arrays in Javascript How to compare arrays in Javascript

Let's say you have two arrays and you want to see if all elements are identical, very importantly not just some but all elements must be the same.

I'll start with some pseudo code of what I think the final solution will end up doing.

1. Null check both arrays. False if either are null

2. Check if the length of the two arrays are the same. If they are not we can exit fast with false.

3. Sort both arrays using the built-in JavaScript array sorter. This will help put them in the same order so it will once again exit faster.

4. Loop one array and compare the second one at the same index. Once again, at the first instance of not a match it will exit fast with false.

Alright, let's now take a look at some code to compare arrays using Javascript:



function arrayEquals(array1, array2) {
if (!array1 || !array2)
return false;
if (array1.length !== array2.length)
return false;
var array1Sorted = array1.slice().sort();
var array2Sorted = array2.slice().sort();
return array1Sorted.every(function(value, index) {
return value === array2Sorted[index];
});
}

The above function returns true or false based on if the arrays are equal. Usage: var areSame = arrayEquals(array1, array2);

As an added bonus, let's convert the above function into an Array extension method:


Array.prototype.equals = function (array2) {
if (!this || !array2)
return false;
if (this.length !== array2.length)
return false;
var array1Sorted = this.slice().sort();
var array2Sorted = array2.slice().sort();
return array1Sorted.every(function(value, index) {
return value === array2Sorted[index];
});
}

Now we can simplify the usage: var areSame = array1.equals(array2);

Published on Jun 13, 2022

Tags: JavaScript | Javascript Arrays Tutorial | compare

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.