Follow @endyourif rss Facebook LinkedIn

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

Published on Jun 13, 2022

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);

Tags: JavaScript | Javascript Arrays Tutorial | compare

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP