How to compare arrays in JavaScript?

Ask a question+

I’d like to compare two arrays… ideally, efficiently. Nothing fancy, just true if they are identical, and false if not. Not surprisingly, the comparison operator doesn’t seem to work.

var a1 = [1,2,3];
var a2 = [1,2,3];
console.log(a1==a2);    // Returns false
console.log(JSON.stringify(a1)==JSON.stringify(a2));    // Returns true

JSON encoding each array does, but is there a faster or “better” way to simply compare arrays without having to iterate through each value?

add comment

1 Answer


// Warn if overriding existing method
console.warn(“Overriding existing Array.prototype.equals. Possible causes: New API defines the method, there’s a framework conflict or you’ve got double inclusions in your code.”);
// attach the .equals method to Array’s prototype to call it on any array
Array.prototype.equals = function (array) {
// if the other array is a falsy value, return
if (!array)
return false;

// compare lengths - can save a lot of time 
if (this.length != array.length)
    return false;

for (var i = 0, l=this.length; i < l; i++) {
    // Check if we have nested arrays
    if (this[i] instanceof Array && array[i] instanceof Array) {
        // recurse into the nested arrays
        if (!this[i].equals(array[i]))
            return false;       
    else if (this[i] != array[i]) { 
        // Warning - two different object instances will never be equal: {x:20} != {x:20}
        return false;   
return true;

// Hide method from for-in loops
Object.defineProperty(Array.prototype, “equals”, {enumerable: false});
[1, 2, [3, 4]].equals([1, 2, [3, 2]]) === false;
[1, “2,3”].equals([1, 2, 3]) === false;
[1, 2, [3, 4]].equals([1, 2, [3, 4]]) === true;
[1, 2, 1, 2].equals([1, 2, 1, 2]) === true;
You may say “But it is much faster to compare strings - no loops…” well, then you should note there ARE loops. First recursive loop that converts Array to string and second, that compares two strings. So this method is faster than use of string.

Azniv Saroyan 150
add comment

Your Answer