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:
[code]
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];
});
}
[/code]
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:
[code]
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];
});
}
[/code]
Now we can simplify the usage: var areSame = array1.equals(array2);