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?

5 upvote
  flag
You could first compare their length, and if they are equal each values. – TJHeuvel
31 upvote
  flag
What makes two arrays equal for you? Same elements? Same order of elements? Encoding as JSON only works as long as the element of the array can be serialized to JSON. If the array can contain objects, how deep would you go? When are two objects "equal"? – Felix Kling
1 upvote
  flag
upvote
  flag
@Blender - possibly, but the examples I did find on SO were only to specifically do something with the arrays, such as outputting all of the elements present in one but not the other, which would entail iterating through each element. Felix, in this case, same elements in the same order. – Julian H. Lam
21 upvote
  flag
@FelixKling, defining "equality" is definitely a subtle topic, but for people coming to JavaScript from higher-level languages, there is no excuse for silliness like ([] == []) == false. – Alex D
upvote
  flag
upvote
  flag
@AlexD it looks like arrays use reference equality which is what you'd expect. It'd be pretty awful if you couldn't do that – Jonny Leeds
upvote
  flag
@AlexD I somewhat can't think of a language where this doesn't happen. In C++, you'd be comparing two pointers - false. In Java, you're doing the same as in javascript. In PHP, something behind the scenes will loop through the arrays - do you call PHP a Higher level language? – Tomáš Zato
upvote
  flag
@TomášZato, there are many such languages. – Alex D
3 upvote
  flag
@AlexD Thanks for giving me exact and useful answer. Are you intentionally prolonging the discussion? – Tomáš Zato
upvote
  flag
[2, 1].toSTring() == [2, 1].toString() – Bart Hoekstra

42 Answers 11

On the same lines as JSON.encode is to use join().

function checkArrays( arrA, arrB ){

    //check if lengths are different
    if(arrA.length !== arrB.length) return false;


    //slice so we do not effect the original
    //sort makes sure they are in order
    //join makes it a string so we can do a string compare
    var cA = arrA.slice().sort().join(","); 
    var cB = arrB.slice().sort().join(",");

    return cA===cB;

}

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];
var c = [1,2,3,4];
var d = [1,2,3,4,6];
var e = ["1","2","3","4","5"];  //will return true

console.log( checkArrays(a,b) );  //true
console.log( checkArrays(a,c) );  //false
console.log( checkArrays(a,d) );  //false
console.log( checkArrays(a,e) );  //true

Only problem is if you care about types which the last comparison tests. If you care about types, you will have to loop.

function checkArrays( arrA, arrB ){

    //check if lengths are different
    if(arrA.length !== arrB.length) return false;

    //slice so we do not effect the orginal
    //sort makes sure they are in order
    var cA = arrA.slice().sort(); 
    var cB = arrB.slice().sort();

    for(var i=0;i<cA.length;i++){
         if(cA[i]!==cB[i]) return false;
    }

    return true;

}

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];
var c = [1,2,3,4];
var d = [1,2,3,4,6];
var e = ["1","2","3","4","5"];

console.log( checkArrays(a,b) );  //true
console.log( checkArrays(a,c) );  //false
console.log( checkArrays(a,d) );  //false
console.log( checkArrays(a,e) );  //false

If the order should remain the same, than it is just a loop, no sort is needed.

function checkArrays( arrA, arrB ){

    //check if lengths are different
    if(arrA.length !== arrB.length) return false;


    for(var i=0;i<arrA.length;i++){
         if(arrA[i]!==arrB[i]) return false;
    }

    return true;

}

var a = [1,2,3,4,5];
var b = [5,4,3,2,1];
var c = [1,2,3,4];
var d = [1,2,3,4,6];
var e = ["1","2","3","4","5"];

console.log( checkArrays(a,a) );  //true
console.log( checkArrays(a,b) );  //false
console.log( checkArrays(a,c) );  //false
console.log( checkArrays(a,d) );  //false
console.log( checkArrays(a,e) );  //false
upvote
  flag
Thanks, @epascarello, in my specific case, I am only comparing the order of elements, not types, so .join(); would work as well. Thanks for the insight. – Julian H. Lam
upvote
  flag
With your first version of checkArrays(): checkArrays([11,22,33,44], [1,12,23,344]) // true – Ja͢ck
upvote
  flag
whoops, should be joined with a separator. :) – epascarello
2 upvote
  flag
This only does work for certain arrays, and will be very slow with big arrays. – Tomáš Zato
upvote
  flag
@TomášZato Of course it will be slow with large arrays. Looping over and comparing will be. Thanks for the downvote on a valid answer, the OP did not say they needed super fast performance. – epascarello
2 upvote
  flag
Generating JSON is looping too, you just (or it seems so) don't know about it. Besides looping, generating JSON also requires more memory - it creates 2 string representations of said arrays before comparing. The downwote function is implemented to order answers from the best to the worst. I think your answer is not a good answer, so I downvoted it. – Tomáš Zato
upvote
  flag
@TomášZato Where is the JSON? In small arrays these solutions are perfectly fine and fast for non complex arrays. The second solution can drop the sort() if it is the same thing and it is a simple for loop. – epascarello
2 upvote
  flag
Sorry, I just said JSON instead of .join(). Maybe if you stated your second solution as primary (as it is the better one, though toothless against multidimensional arrays), I would not judge you that way. So far, I downoted all answers that do convert arrays to strings. As well, I upvoted all that use the right way, in case you needed that to know. This means @Tim Down's answer and Bireys one. – Tomáš Zato
5 upvote
  flag
First version FAILS: checkArrays([1,2,3] , ["1,2",3]) == true, and it's very unlikely that that's what you want to happen! – Doin
upvote
  flag
@Doin, so use a separator that is unique if you know the array content will contain certain characters. join("~~!!@@##$$%%^^&&**") – epascarello
2 upvote
  flag
@epascarello: Yes, you can but (aside from the inefficiency of the very long separator you suggest) it means there will be edge cases (where the array happens to contain a string with your separator in it) where the checkArrays() function misbehaves. This might not be a problem if you know something about the contents of the arrays (so you can choose a separator you're sure won't be in the array items), but if you're trying to write a general array-comparison function, then using join() like this makes it subtly buggy! – Doin
2 upvote
  flag
...you could fix it using some kind of string escaping mechanism, such as replacing "\" with "\\" followed by replacing "," with "\#" (for example), prior to join()ing (ensuring that the individual strings to be joined never contain commas). However given the effort and inefficiency of this approach, you'd be much better off just looping through the array elements! – Doin
upvote
  flag
Note that the sort() call will modify the input arrays - this might not be desirable. – try-catch-finally
upvote
  flag
So clone it.... – epascarello

JSON.parse would also iterate through each value anyway so I guess it would be better to compare iterating through each value and reduce some steps of execution ( like encoding it into JSON ).

upvote
  flag
Oh, that is a good point. Were I using PHP, I'd elect to use md5();. – Julian H. Lam
upvote
  flag
In JavaScript JSON has only parse() and stringify() methods. Check it yourself: console.dir(JSON). – Pavlo
upvote
  flag
thank you for being so precise. parse() is what i meant. It is a logical answer and not code. That is why it is in text and not in the code. – Birey

It's unclear what you mean by "identical". For example, are the arrays a and b below identical (note the nested arrays)?

var a = ["foo", ["bar"]], b = ["foo", ["bar"]];

Here's an optimized array comparison function that compares corresponding elements of each array in turn using strict equality and does not do recursive comparison of array elements that are themselves arrays, meaning that for the above example, arraysIdentical(a, b) would return false. It works in the general case, which JSON- and join()-based solutions will not:

function arraysIdentical(a, b) {
    var i = a.length;
    if (i != b.length) return false;
    while (i--) {
        if (a[i] !== b[i]) return false;
    }
    return true;
};
upvote
  flag
This question is missing the inside array comparisons, right? – Jadiel de Armas
upvote
  flag
@ASDF: It's unclear from the question what "identical" means. Obviously this answer just does a shallow check. I'll add a note. – Tim Down
upvote
  flag
this fails for arraysIdentical([1, 2, [3, 2]],[1, 2, [3, 2]]); – Gopinath Shiva
4 upvote
  flag
@GopinathShiva: Well, it only fails if you're expecting it to return true. The answer explains that it won't. If you need to compare nested arrays, you could easily add a recursive check. – Tim Down
up vote 664 down vote accepted

I can't really believe that so many people want to compare arrays as strings. So, though this is old question, I will add the right way to compare arrays - loop through them and compare every value:

The right way:

// Warn if overriding existing method
if(Array.prototype.equals)
    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});

Usage:

[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.

I believe that larger amounts of data should be always stored in arrays, not in objects. However if you use objects, they can be partially compared too.
Here's how:

Comparing objects:

I've stated above, that two object instances will never be equal, even if they contain same data at the moment:

({a:1, foo:"bar", numberOfTheBeast: 666}) == ({a:1, foo:"bar", numberOfTheBeast: 666})  //false

This has a reason, since there may be, for example private variables within objects.

However, if you just use object structure to contain data, comparing is still possible:

Object.prototype.equals = function(object2) {
    //For the first loop, we only check for types
    for (propName in this) {
        //Check for inherited methods and properties - like .equals itself
        //https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwnProperty
        //Return false if the return value is different
        if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
            return false;
        }
        //Check instance type
        else if (typeof this[propName] != typeof object2[propName]) {
            //Different types => not equal
            return false;
        }
    }
    //Now a deeper check using other objects property names
    for(propName in object2) {
        //We must check instances anyway, there may be a property that only exists in object2
            //I wonder, if remembering the checked values from the first loop would be faster or not 
        if (this.hasOwnProperty(propName) != object2.hasOwnProperty(propName)) {
            return false;
        }
        else if (typeof this[propName] != typeof object2[propName]) {
            return false;
        }
        //If the property is inherited, do not check any more (it must be equa if both objects inherit it)
        if(!this.hasOwnProperty(propName))
          continue;

        //Now the detail check and recursion

        //This returns the script back to the array comparing
        /**REQUIRES Array.equals**/
        if (this[propName] instanceof Array && object2[propName] instanceof Array) {
                   // recurse into the nested arrays
           if (!this[propName].equals(object2[propName]))
                        return false;
        }
        else if (this[propName] instanceof Object && object2[propName] instanceof Object) {
                   // recurse into another objects
                   //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
           if (!this[propName].equals(object2[propName]))
                        return false;
        }
        //Normal value comparison for strings and numbers
        else if(this[propName] != object2[propName]) {
           return false;
        }
    }
    //If everything passed, let's say YES
    return true;
}  

However, remember that this one is to serve in comparing JSON like data, not class instances and other stuff. If you want to compare mor complicated objects, look at this answer and it's superlong function.
To make this work with Array.equals you must edit the original function a little bit:

...
    // 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;
    }
    /**REQUIRES OBJECT COMPARE**/
    else if (this[i] instanceof Object && array[i] instanceof Object) {
        // recurse into another objects
        //console.log("Recursing to compare ", this[propName],"with",object2[propName], " both named \""+propName+"\"");
        if (!this[i].equals(array[i]))
            return false;
        }
    else if (this[i] != array[i]) {
...

I made a little test tool for both of the functions.

Bonus: Nested arrays with indexOf and contains

Samy Bencherif has prepared useful functions for the case you're searching for a specific object in nested arrays, which are available here: https://jsfiddle.net/SamyBencherif/8352y6yw/

3 upvote
  flag
Thanks for your input. Given its view count, I suppose many users redirected here from Google are having the same conundrum of figuring out exactly how to compare two arrays "properly"! – Julian H. Lam
19 upvote
  flag
If you want to do strict comparisons use this[i] !== array[i] instead of !=. – Tim S.
29 upvote
  flag
Your method should be called equals instead of compare. At least in .NET, compare usually returns a signed int indicating which object is greater than the other. See: Comparer.Compare. – Oliver
upvote
  flag
It fails on comparing arrays with the same values but different order. Please check my suggestion //allinonescript.com/a/16944097/1494393 – Igor S.
6 upvote
  flag
+1 for the answer and a beer to your health for writing the function in the array prototype. – Luca Fagioli
4 upvote
  flag
Nice answer... but shouldn't you be caching the array length for the loop: for (var i = 0, len = this.length; i < len; i++) – Willshaw Media
13 upvote
  flag
Nt only is this the right way of doing it, it's also considerable more efficent. Here's a quick jsperf script I prepared for all the methods suggested in this question. jsperf.com/comparing-arrays2 – Tolga E
3 upvote
  flag
So actually, placing the function on the array prototype is probably not the right thing to do. Messing with the global objects like this can cause weird problems in code you didn't write - or code you did... – B T
upvote
  flag
This works great! However, I needed to compare arrays of objects. I used JSON.stringify(Object) for the comparison. gist.github.com/harmstyler/7896595 – harmstyler
upvote
  flag
Nope, even this can be handled. For comparing objects, you need to use for(var i in object). For {a:1, b:2, c:666} i will become ("a", "b", "c") in that order. – Tomáš Zato
upvote
  flag
@WillshawMedia oh, you're right! – Tomáš Zato
1 upvote
  flag
Wouldn't be a bad idea to make this code "strict mode" safe, by changing your first condition to if (!this || !array). It would be a rare but possible case where you'd get a TypeError on this.length because the this value was set to null or undefined. – cookie monster
upvote
  flag
And would it still have a method .compare? – Tomáš Zato
1 upvote
  flag
I am surprised that there are no native functions to compare array, do I really need to copy paste your code for it to work? It seems something that should just be included in the language. – Pinocchio
1 upvote
  flag
I think the problem is, that array comparing implementation may vary depending on what you need. If you just read the comments and other answers, you'll see that my code hardly covers everything that may be understood as array comparing. – Tomáš Zato
upvote
  flag
TomášZato good point but I still agree with Pinocchio. Event if it can be understood differently by different people, Evan's solution with the "strict" mode and renaming to .equals is a feature that would improve the overall quality of js scripts, since we can understand that many people don't see the for loops beyond the ones they write. Also, official documentation exists to solve the "many possible interpretations of what a .equals function should do" problem. – Johnride
upvote
  flag
To be honest, this function is damn too slow when you need to compare it quick (for example in mousemove event)... – Flash Thunder
upvote
  flag
And which is faster? – Tomáš Zato
1 upvote
  flag
Note that with this code, you wont be able to do for (var i in myArray) { } because equals() is now a property and the loop will now loop once on this property. – Olivier Pons
1 upvote
  flag
You should never loop through array like this. I remember that, in past when I was learning javascript, i would also contain "length" and other default properties. (in ancient IE) – Tomáš Zato
57 upvote
  flag
Changing a built-in type's prototype is definitely not the right way – Jasper
upvote
  flag
@Jasper Array.equals is not a built-in prototype according to ECMAScript specs. Please check your sources again. – Tomáš Zato
4 upvote
  flag
@TomášZato Yes, but Array is. The point is, that since Array is a built-in, you shouldn't modify its prototype. – Jasper
upvote
  flag
@Jasper Why not? Anyway, you can easily rewrite my function to a procedural version, instead of the OOP one. – Tomáš Zato
9 upvote
  flag
@TomášZato basically, because in the future there might be a an equals() function on the Array prototype, and if it's different (e.g. deep vs shallow comparisons, or even just adding a parameter to allow selection of deep or shallow comparison) your code suddenly starts breaking other scripts that use this function... – Jasper
22 upvote
  flag
Besides, it's not about whether it's easy to rewrite, it's about the fact that an answer shouldn't recommend something that's considered bad practice (developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/…) and should definitely not do this below the header "The right way" – Jasper
upvote
  flag
I made a non-prototypal version of your array equals function here: //allinonescript.com/questions/27852356/… – firstdoit
1 upvote
  flag
I really appreciate you to give such this effort to give your input. salute u – Piyush Dholariya
upvote
  flag
@Jasper, @TomášZato: I recognised that extending prototype can be an issue, hence what I usually do is to enclosure that prototype with if(typeof Array.prototype.equals != 'function') { ... }... Not ideal, but certainly a workaround. – Robert Sim
1 upvote
  flag
@RobertSim And to be completelly correct, you could raise a warning in the console :) – Tomáš Zato
1 upvote
  flag
@TomášZato ah. i didn't think of that. I have been working on short term projects to consider the warnings. thanks. :) – Robert Sim
2 upvote
  flag
@RobertSim No. That doesn't work around the problem, it just shows that you have seen others who do that and copied them. Imagine the standard defining an equals for arrays which compares all members of the array using ===. Now, code using your function will work incorrectly (because Array.equals() does something other than expected) in browsers that implement this new function. In browsers that do not have the new function, code using the new standard function, will appear to work, but not do what is expected. – Jasper
2 upvote
  flag
Combining code using your function and the new function has become impossible. Adding polyfills to the mix makes things worse: now it works one way if your code is executed first than when the polyfill is executed first. Even if no such function is added to the standard, all the same problems occur if someone else decides to do the same as you, but has a different opinion on what equals should do... And showing an Exception does not solve any problems. It would be a good option if you had to do this, but as you said yourself, you don't have to; you can easily convert this to a normal function. – Jasper
5 upvote
  flag
No, you should only add a function to the prototype if you know exactly what the function should do. This is basically only the case for polyfills... – Jasper
upvote
  flag
@Jasper, RobertSim, Tomáš Zato: Jasper is obviously right, I don't even perceive a debate -- as soon as we introduce multiple independent codebases in the same environment (a single third-party library will do) then all arguments for modifying a shared prototype become moot. It used to be that we couldn't subclass arrays, but as of January 2015 it seems that ES6 semantics allow for a clean way to do this. – tne
1 upvote
  flag
@tne There's no right or wrong in fact. There's a group of people that think they have some patent on the bug wisdom how programs should be written. It's a lie. It only shows how close minded some can be and how flexibility is unknown word for some. Clearly, in big, long-term applications and frameworks, one should think twice before defining any single function name and definitelly defining custom prototype functions for built-in types could turn out to be a bad idea after 5 years. But not everybody is making a program that should last 5 years. You can enjoy your clumsy... – Tomáš Zato
1 upvote
  flag
@tne ... overkill designs. But do others the courtesy of letting them enjoy the comfort of swift and clean code with as few type strokes as possible. Some of us just like getters, setters, operator overloading and writing own built in prototypes because we're creative and we like to change the language we're using. And in 5 years, whatever we've been writing will be long forgotten and won't matter. – Tomáš Zato
2 upvote
  flag
@TomášZato I definitely accept all your arguments whenever you have a single codebase, especially if it's short-lived as you say. If you (1) include any third-party library (which is extremely common nowadays) and (2) the code has a small chance to still be in use for ES7+, then you accept that your application might suddenly start crashing (or worse, display silent but incorrect behavior that you might never know about) as soon as users upgrade their runtimes (browsers, server-side envs,...). I admit I'm a bit irritated that you consider subclassing "overkill", it's exactly what you want. – tne
2 upvote
  flag
@tne Subclassed array can be only used with new ImprovedArray() whereas my solution works on anything instantiated as [] no matter whether it comes from external source, parsed JSON or your program. My answer has been here for 2 years and is still valid and doesn't break anything (only irritates some people which I don't care about). Observational evidence is the only thing superior to logical arguments (and what you say is logical and true). Meanwhile anybody who cares about the code he writes will read your comments and make his decision with your advice on mind. – Tomáš Zato
upvote
  flag
@TomášZato Why yes, that's the whole point; to avoid polluting the global prototype. I must stress that's it's absolutely trivial to wrap any array in such a subtype; so the difference is between "opt-in" vs "mandatory" custom behavior for third-parties. In a weird way I respect your nonchalant attitude toward what you might perceive as cargo-culting, but unfortunately it's these kinds of practices that force spec writers to weird corners just to avoid "breaking" software that was in fact already broken. Many languages have standard default equals functionality, it's not inconceivable for JS. – tne
7 upvote
  flag
@TomášZato I agree with you that you can do whatever you want in your own code. You may not run into any of the problems, but if you do, you only shot yourself in the foot. However, we're talking about a recommendation on a public website, and one which calls itself "The right way" at that. The same reasoning does not go, and you shouldn't shoot other people in the foot. – Jasper
1 upvote
  flag
@Jasper If you wanna go all analogic on me, please keep on mind that my post is merely a recommendation how to shoot yourself in the leg. I still do not think the whole problem is as terrible as you picture it. As I mentioned, for 2 years nothing changed. I doubt another 2 will bring anything new. If they do, I am here to update the question - not a second before. Long investments that don't pay off kill the fun in programming. – Tomáš Zato
5 upvote
  flag
@TomášZato Recommendations on how to shoot yourself in the leg don't belong on this site (unless the question is "how do I shoot myself in the leg"). And your "I'll update the answer" shows you still don't understand the problems. Because at that point, anyone who used this code, isn't here to see your update and yet is feeling the pain in his foot. And how about two people following this strategy? Their code can't be used on the same site. Your answer might work (in some circumstances), but that doesn't make it any less wrong... – Jasper
upvote
  flag
@TomášZato thanks for the answer, inspired me to write a similar solution for a future release for firebrickjs – Stevanicus
3 upvote
  flag
Your Array.ptototype.equals should use a strict comparaison. Else things like [[]].equals([false]); will return true. – dievardump
upvote
  flag
@dievardump Strict comparison in non-typed languages has also it's pitfalls (1 vs "1"). Anyway I don't think [[]].equals([false]); would return true by just looking on the code. Have you tested that? – Tomáš Zato
upvote
  flag
Yes here : jsfiddle.net/ku9uw18k -- since [] != false === false your code never return false. Would be the same with [""].equals([false]); and for me [1].equals(["1"]) should return false – dievardump
upvote
  flag
@dievardump Thanks, good to know that. Anyway I was considering strict comparison and I concluded, as I was already pointing out, that most people will desire "1" and 1 to be equal. Those like you, who are aware of the typing in javascript, will be skilled enough to edit the code to their needs. My code is just a template for you. – Tomáš Zato
2 upvote
  flag
This is apparently a pretty hot topic.. I found myself disappointed with how js builtins didn't handle nested arrays correctly. So using @TomášZato 's code, I've created a contains and indexOf function, which much like Zato's equals function, properly handle nested arrays. All the functions are added to the Array prototype. The code is available here: jsfiddle.net/SamyBencherif/8352y6yw – Samy Bencherif
upvote
  flag
true.equals(false) equates to true, and false.equals(true) also equates to true using this method, pretty funny for the giggles but I imagine when comparing object.equals(false) you'd get unexpected results. – Kade Hafen
upvote
  flag
Seems like great. But if arrays have same values in different orders, it returns false. This should be corrected, cause this is very important. – Otvazhnii
upvote
  flag
@MrEvgenyShcherbina This is intended. You have to sort the arrays if you want to compare them regardless of order of values. – Tomáš Zato
upvote
  flag
How could such a simple task warrant so many lines of code?? I feel like I need to deploy a microservice to use this solution. – rigdonmr

In my case compared arrays contain only numbers and strings. This function will show you if arrays contain same elements.

function are_arrs_match(arr1, arr2){
    return arr1.sort().toString() === arr2.sort().toString()
}

Let's test it!

arr1 = [1, 2, 3, 'nik']
arr2 = ['nik', 3, 1, 2]
arr3 = [1, 2, 5]

console.log (are_arrs_match(arr1, arr2)) //true
console.log (are_arrs_match(arr1, arr3)) //false
upvote
  flag
The question doesn't ask you to sort, so your solution is wrong for examples like are_arrs_equal([1,2], [2,1]). Also, see other discussions on this page for why stringifying is unnecessary, fragile, and wrong. – phyzome
upvote
  flag
are_arrs_equal([1,2], [2,1]) returns true as expected. Perhaps this solution is not ideal, but it worked for me. – yesnik
upvote
  flag
That's precisely the problem, those two are not equal in any sane sense of the word "equal" for an ordered data structure. They're arrays, not sets, and if you want set equality you should call it that -- and be answering a different question. :-) – phyzome
upvote
  flag
You're right! :) I'll rename this method to are_arrs_match(arr1, arr2) . Yes, it doesn't check equality of arrays, but it can say if they contain the same elements. – yesnik
1 upvote
  flag
I agree with the comments above, but this solution also works for me in my simple arrays of integers, where order is not important, so I will use it. – tomazahlin
1 upvote
  flag
Fails for are_arrs_match([1,2], ["1,2"]) (returns true). And note that the sort() call will modify the input arrays - this might not be desirable. – try-catch-finally

Herer's my solution:

/**
 * Tests two data structures for equality
 * @param {object} x
 * @param {object} y
 * @returns {boolean}
 */
var equal = function(x, y) {
    if (typeof x !== typeof y) return false;
    if (x instanceof Array && y instanceof Array && x.length !== y.length) return false;
    if (typeof x === 'object') {
        for (var p in x) if (x.hasOwnProperty(p)) {
            if (typeof x[p] === 'function' && typeof y[p] === 'function') continue;
            if (x[p] instanceof Array && y[p] instanceof Array && x[p].length !== y[p].length) return false;
            if (typeof x[p] !== typeof y[p]) return false;
            if (typeof x[p] === 'object' && typeof y[p] === 'object') { if (!equal(x[p], y[p])) return false; } else
            if (x[p] !== y[p]) return false;
        }
    } else return x === y;
    return true;
};

Works with any nested data structure, and obviously ignores objects' methods. Don't even think of extending Object.prototype with this method, when I tried this once, jQuery broke ;)

For most arrays it's still faster than most of serialization solutions. It's probably the fastest compare method for arrays of object records.

upvote
  flag
no good! these give true: equal({}, {a:1}) and equal({}, null) and this errors out: equal({a:2}, null) – kristianlm

Extending Tomáš Zato idea. Tomas's Array.prototype.compare should be infact called Array.prototype.compareIdentical.

It passes on:

[1, 2, [3, 4]].compareIdentical ([1, 2, [3, 2]]) === false;
[1, "2,3"].compareIdentical ([1, 2, 3]) === false;
[1, 2, [3, 4]].compareIdentical ([1, 2, [3, 4]]) === true;
[1, 2, 1, 2].compareIdentical ([1, 2, 1, 2]) === true;

But fails on:

[[1, 2, [3, 2]],1, 2, [3, 2]].compareIdentical([1, 2, [3, 2],[1, 2, [3, 2]]])

Here is better (in my opinion) version:

Array.prototype.compare = 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;

    this.sort();
    array.sort();
    for (var i = 0; i < this.length; i++) {
        // Check if we have nested arrays
        if (this[i] instanceof Array && array[i] instanceof Array) {
            // recurse into the nested arrays
            if (!this[i].compare(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;
}

http://jsfiddle.net/igos/bcfCY/

2 upvote
  flag
-1. If it 'fails' on the example you've given, then that's only the case for a somewhat arbitrary definition of 'fails'. Why would you expect those two different arrays to be considered equal? You haven't even explained what concept of 'equality' you're trying to implement here, or why it's a sensible or helpful one, but it looks like you want multidimensional arrays to be compared as if they were collapsed down to single-dimensional ones. If so, you didn't even achieve that: [1,2].compare([[1,2]]) gives false with your version, just as with Tomáš's. – Mark Amery
upvote
  flag
Based on what I could infer, he's saying that [1, 2, 3, 4] and [1, 3, 2, 4] should be compared as equal (Order doesn't matter). – Gautham Badhrinathan
1 upvote
  flag
I agree that both versions satisfy different definitions of 'equal' but I don't think it should be -1 so +1 from me – OrganicPanda

Building off Tomáš Zato's answer, I agree that just iterating through the arrays is the fastest. Additionally (like others have already stated), the function should be called equals/equal, not compare. In light of this, I modified the function to handle comparing arrays for similarity - i.e. they have the same elements, but out of order - for personal use, and thought I'd throw it on here for everyone to see.

Array.prototype.equals = function (array, strict) {
    if (!array)
        return false;

    if (arguments.length == 1)
        strict = true;

    if (this.length != array.length)
        return false;

    for (var i = 0; i < this.length; i++) {
        if (this[i] instanceof Array && array[i] instanceof Array) {
            if (!this[i].equals(array[i], strict))
                return false;
        }
        else if (strict && this[i] != array[i]) {
            return false;
        }
        else if (!strict) {
            return this.sort().equals(array.sort(), true);
        }
    }
    return true;
}

This function takes an additional parameter of strict that defaults to true. This strict parameter defines if the arrays need to be wholly equal in both contents and the order of those contents, or simply just contain the same contents.

Example:

var arr1 = [1, 2, 3, 4];
var arr2 = [2, 1, 4, 3];  // Loosely equal to 1
var arr3 = [2, 2, 3, 4];  // Not equal to 1
var arr4 = [1, 2, 3, 4];  // Strictly equal to 1

arr1.equals(arr2);         // false
arr1.equals(arr2, false);  // true
arr1.equals(arr3);         // false
arr1.equals(arr3, false);  // false
arr1.equals(arr4);         // true
arr1.equals(arr4, false);  // true

I've also written up a quick jsfiddle with the function and this example:
http://jsfiddle.net/Roundaround/DLkxX/

for single dimension array you can simply use:

arr1.sort().toString() == arr2.sort().toString()

this will also take care of array with mismatched index.

upvote
  flag
You can use strict equality checking === (to make linter happy) if the arrays in question actually contain string elements. – TranslucentCloud
2 upvote
  flag
Fails for [1,2] and ["1,2"]. Note that the sort() call will modify the input arrays - this might not be desirable. – try-catch-finally

My solution compares Objects, not Arrays. This would work in the same way as Tomáš's as Arrays are Objects, but without the Warning:

Object.prototype.compare_to = function(comparable){

    // Is the value being compared an object
    if(comparable instanceof Object){

        // Count the amount of properties in @comparable
        var count_of_comparable = 0;
        for(p in comparable) count_of_comparable++;

        // Loop through all the properties in @this
        for(property in this){

            // Decrements once for every property in @this
            count_of_comparable--;

            // Prevents an infinite loop
            if(property != "compare_to"){

                // Is the property in @comparable
                if(property in comparable){

                    // Is the property also an Object
                    if(this[property] instanceof Object){

                        // Compare the properties if yes
                        if(!(this[property].compare_to(comparable[property]))){

                            // Return false if the Object properties don't match
                            return false;
                        }
                    // Are the values unequal
                    } else if(this[property] !== comparable[property]){

                        // Return false if they are unequal
                        return false;
                    }
                } else {

                    // Return false if the property is not in the object being compared
                    return false;
                }
            }
        }
    } else {

        // Return false if the value is anything other than an object
        return false;
    }

    // Return true if their are as many properties in the comparable object as @this
    return count_of_comparable == 0;
}

Hope this helps you or anyone else searching for an answer.

while this only works for scalar arrays, it is short & sweet:

a1.length==a2.length && a1.every(function(v,i) { return v === a2[i]})

or, in ECMAScript 6/CoffeeScript/TypeScript with Arrow Functions:

a1.length==a2.length && a1.every((v,i)=> v === a2[i])
8 upvote
  flag
I like this, although readers should be aware this only works on sorted arrays. – Ellen Spertus
7 upvote
  flag
Why doesn't this suggestion have more upvotes? Am I missing some crucial drawback (except that it's not working in IE < 9)? – Peppe L-G
5 upvote
  flag
It works on any kind of arrays, sorted or not @espertus – Michał Miszczyszyn
1 upvote
  flag
@MichałMiszczyszyn Are you sure? I am not a JS expert, but it looks to me as though the function is only true if the i-th element of a1 is equal to the i-th element of a2. – Ellen Spertus
16 upvote
  flag
Yes, exactly. This function is supposed to compare two arrays, it doesn't matter if they're sorted or not, their consecutive elements have to be equal. – Michał Miszczyszyn
10 upvote
  flag
@espertus Indeed, it won't return true if the elements do not have the exact same order in both arrays. However, the goal of an equality check is not to check if they contains the same elements but to check if they have the same element in the same orders. – Quentin Roy
3 upvote
  flag
If you want to check if both arrays are equals, containing the same unsorted items (but not used multiple times), you can use a1.length==a2.length && a1.every((v,i)=>a2.includes(v)): var a1 =[1,2,3], a2 = [3,2,1]; (var a1 =[1,3,3], a2 = [1,1,3]; will not work as expected) – mems
2 upvote
  flag
This is a great answer, although it comes with a caveat. The answerer even highlights the caveat: this works only for scalar arrays but I think many people may overlook that detail due to word scalar being used, something I assume most of don't hear often. Might do this question justice by touching up on that piece and further clarifying the example... – Govind Rai
upvote
  flag
Decided to edit the question cuz OCD. Hope it gets past the review gods. – Govind Rai
1 upvote
  flag
Please explain "scalar" (by editing the answer) – try-catch-finally
upvote
  flag
best answer thanx – shady sherif
upvote
  flag
@GovindRai Thanks! you just wrote an entire paragraph and let the most important detail out (you should have explained "scalar"s at the end). – Taurus
upvote
  flag
Note that the length check has another positive side-effect, if the lengths are unequal, the second operand of && won't be evaluated, so better performance. – Taurus

I like to use the Underscore library for array/object heavy coding projects ... in Underscore and Lodash whether you're comparing arrays or objects it just looks like this:

_.isEqual(array1, array2)   // returns a boolean
_.isEqual(object1, object2) // returns a boolean
13 upvote
  flag
Note that order matters _.isEqual([1,2,3], [2,1,3]) => false – Vitaliy Alekask
2 upvote
  flag
or if you want just the isEqual functionality, you can always use the lodash.isequal module – hellatan
1 upvote
  flag
You can maybe use _.difference(); if order does not matter to you – Ronan Quillevere
upvote
  flag
We can sort the array before this check if the order doesnt matter _.isEqual([1,2,3].sort(), [2,1,3].sort()) => true – Filype
function compareArrays(arrayA, arrayB) {
    if (arrayA.length != arrayB.length) return true;
    for (i = 0; i < arrayA.length; i++)
        if (arrayB.indexOf(arrayA[i]) == -1) {
            return true;
        }
    }
    for (i = 0; i < arrayB.length; i++) {
        if (arrayA.indexOf(arrayB[i]) == -1) {
            return true;
        }
    }
    return false;
}

Here's a CoffeeScript version, for those who prefer that:

Array.prototype.equals = (array) ->
  return false if not array # if the other array is a falsy value, return
  return false if @length isnt array.length # compare lengths - can save a lot of time

  for item, index in @
    if item instanceof Array and array[index] instanceof Array # Check if we have nested arrays
      if not item.equals(array[index]) # recurse into the nested arrays
        return false
    else if this[index] != array[index]
      return false # Warning - two different object instances will never be equal: {x:20} != {x:20}
  true

All credits goes to @tomas-zato.

upvote
  flag
Array::equals – alex

If the array is plain and the order is matter so this two lines may help

//Assume
var a = ['a','b', 'c']; var b = ['a','e', 'c'];  

if(a.length !== b.length) return false;
return !a.reduce(
  function(prev,next,idx, arr){ return prev || next != b[idx] },false
); 

Reduce walks through one of array and returns 'false' if at least one element of 'a' is nor equial to element of 'b' Just wrap this into function

upvote
  flag
map, reduce, filter everything! :P – Thoran
upvote
  flag
This is a bad solution because Array.prototype.reduce will walk through every element in a even if the first compared elements do not match. Also using !a and != in the loop is a double negative which makes this answer more complicated (and hard to read) than it needs to be – naomik
upvote
  flag
Agree. There is some some() function :) Two years ago i didn't know it. But double negation still will be there. – Serge

This I think is the simplest way to do it using JSON stringify, and it may be the best solution in some situations:

JSON.stringify(a1) === JSON.stringify(a2);

This converts the objects a1 and a2 into strings so they can be compared. The order is important in most cases, for that can sort the object using a sort algorithm shown in one of the above answers.

Please do note that you are no longer comparing the object but the string representation of the object. It may not be exactly what you want.

upvote
  flag
good answer but why []==[] return false ? both are simple objects then why ? – Pardeep Jain
2 upvote
  flag
@PardeepJain, this is because by default, the equality operator in ECMAScript for Objects returns true when they reference the same memory location. Try var x = y = []; // now equality returns true. – radtek
3 upvote
  flag
just to note that JSON stringify function is not quick. Used with larger arrays will definitely introduce lag. – Lukas Liesis
1 upvote
  flag
The question specifically asks whether there is a better/faster way than using JSON.stringify. – Don Hatch
upvote
  flag
It gets into more detail on why this may be a good solution for some situations. – radtek
upvote
  flag
And this explains JSON.stringify() and how it can be the best choice depending on what you are trying to do. I shared what I found and it looks like its helping others decide. – radtek

I use this code with no issues so far:

if(a.join() == b.join())
    ...

It works even if there are commas in an item.

1 upvote
  flag
commas in an item fails for me: ["1","2"].join() == ["1,2"].join() – Bernard
1 upvote
  flag
["1","2"].join('') == ["1,2"].join('') works. – frostymarvelous
1 upvote
  flag
i do prefer this as i am doing a very simple equality test. so thanks. – frostymarvelous
1 upvote
  flag
Joining with an empty string just changes the broknen-ness slightly, but does not fix it. ["1","2"] and ["12"] will be treated as equal. – Andrew Medico

this script compares Object, Arrays and multidimensional array

function compare(a,b){
     var primitive=['string','number','boolean'];
     if(primitive.indexOf(typeof a)!==-1 && primitive.indexOf(typeof a)===primitive.indexOf(typeof b))return a===b;
     if(typeof a!==typeof b || a.length!==b.length)return false;
     for(i in a){
          if(!compare(a[i],b[i]))return false;
     }
     return true;
}

first line checks whether it's a primitive type. if so it compares the two parameters.

if they are Objects. it iterates over the Object and check every element recursivly.

Usage:

var a=[1,2,[1,2]];
var b=[1,2,[1,2]];
var isEqual=compare(a,b);  //true

This function compares two arrays of arbitrary shape and dimesionality:

function equals(a1, a2) {

    if (!Array.isArray(a1) || !Array.isArray(a2)) {
        throw new Error("Arguments to function equals(a1, a2) must be arrays.");
    }

    if (a1.length !== a2.length) {
        return false;
    }

    for (var i=0; i<a1.length; i++) {
        if (Array.isArray(a1[i]) && Array.isArray(a2[i])) {
            if (equals(a1[i], a2[i])) {
                continue;
            } else {
                return false;
            }
        } else {
            if (a1[i] !== a2[i]) {
                return false;
            }
        }
    }

    return true;
}

Additionally, I have converted Thomas' solution to order free comparison as I needed.

Array.prototype.equalsFreeOrder = function (array) {
    var isThisElemExist;
    if (!array)
        return false;

    if (this.length != array.length)
        return false;

    for (var i = 0; i < this.length; i++) {
        isThisElemExist = false;
        for (var k = 0; k < this.length; k++) {
            if (this[i] instanceof Array && array[k] instanceof Array) {
                if (this[i].equalsFreeOrder(array[k]))
                    isThisElemExist = true;
            }
            else if (this[i] == array[k]) {
                isThisElemExist = true;
            }
        }
        if (!isThisElemExist)
            return false;
    }
    return true;
}

If you are using a testing framework like Mocha with the Chai assertion library, you can use deep equality to compare arrays.

expect(a1).to.deep.equal(a2)

This should return true only if the arrays have equal elements at corresponding indices.

You can disqualify "sameness" if the number of elements do not match or if one of the elements is not in the other's array. Here is simple function that worked for me.

    function isSame(arr1,arr2) {
        var same=true;
        for(var i=0;i < arr1.length;i++) {
            if(!~jQuery.inArray(arr1[i],arr2) || arr1.length!=arr2.length){
                same=false;
                }
            }
        return same;
        }

The reason is that identity or strict operator (===), it compares with no type conversion, that means if both values doesn’t have the same value and the same type, they won’t be considered equal.

take a look this link, it takes you out of doubt easy way to understand how identity operator works

We could do this the functional way, using every (https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/every)

function compareArrays(array1, array2) {
    if (array1.length === array2.length)
        return array1.every((a, index) => a === array2[index])
    else
        return false
}

// test
var a1 = [1,2,3];
var a2 = [1,2,3];

var a3 = ['a', 'r', 'r', 'a', 'y', '1']
var a4 = ['a', 'r', 'r', 'a', 'y', '2']

console.log(compareArrays(a1,a2)) // true
console.log(compareArrays(a1,a3)) // false
console.log(compareArrays(a3,a4)) // false

The Practical Way

I think it's wrong to say a particular implementation is "The Right Way™" if it's only "right" ("correct") in contrast to a "wrong" solution. Tomáš's solution is a clear improvement over string-based array comparison, but that doesn't mean it's objectively "right". What is right anyway? Is it the fastest? Is it the most flexible? Is it the easiest to comprehend? Is it the quickest to debug? Does it use the least operations? Does it have any side effects? No one solution can have the best of all the things.

Tomáš's could say his solution is fast but I would also say it is needlessly complicated. It tries to be an all-in-one solution that works for all arrays, nested or not. In fact, it even accepts more than just arrays as an input and still attempts to give a "valid" answer.


Generics offer reusability

My answer will approach the problem differently. I'll start with a generic arrayCompare procedure that is only concerned with stepping through the arrays. From there, we'll build our other basic comparison functions like arrayEqual and arrayDeepEqual, etc

// arrayCompare :: (a -> a -> Bool) -> [a] -> [a] -> Bool
const arrayCompare = f => ([x,...xs]) => ([y,...ys]) =>
  x === undefined && y === undefined
    ? true
    : Boolean (f (x) (y)) && arrayCompare (f) (xs) (ys)

In my opinion, the best kind of code doesn't even need comments, and this is no exception. There's so little happening here that you can understand the behaviour of this procedure with almost no effort at all. Sure, some of the ES6 syntax might seem foreign to you now, but that's only because ES6 is relatively new.

As the type suggests, arrayCompare takes comparison function, f, and two input arrays, xs and ys. For the most part, all we do is call f (x) (y) for each element in the input arrays. We return an early false if the user-defined f returns false – thanks to &&'s short-circuit evaluation. So yes, this means the comparator can stop iteration early and prevent looping through the rest of the input array when unnecessary.


Strict comparison

Next, using our arrayCompare function, we can easily create other functions we might need. We'll start with the elementary arrayEqual

// equal :: a -> a -> Bool
const equal = x => y =>
  x === y // notice: triple equal

// arrayEqual :: [a] -> [a] -> Bool
const arrayEqual =
  arrayCompare (equal)

const xs = [1,2,3]
const ys = [1,2,3]
console.log (arrayEqual (xs) (ys))      //=> true
// (1 === 1) && (2 === 2) && (3 === 3)  //=> true

const zs = ['1','2','3']
console.log (arrayEqual (xs) (zs))      //=> false
// (1 === '1')                          //=> false

Simple as that. arrayEqual can be defined with arrayCompare and a comparator function that compares a to b using === (for strict equality).

Notice that we also define equal as it's own function. This highlights the role of arrayCompare as a higher-order function to utilize our first order comparator in the context of another data type (Array).


Loose comparison

We could just as easily defined arrayLooseEqual using a == instead. Now when comparing 1 (Number) to '1' (String), the result will be true

// looseEqual :: a -> a -> Bool
const looseEqual = x => y =>
  x == y // notice: double equal

// arrayLooseEqual :: [a] -> [a] -> Bool
const arrayLooseEqual =
  arrayCompare (looseEqual)

const xs = [1,2,3]
const ys = ['1','2','3']
console.log (arrayLooseEqual (xs) (ys))    //=> true
// (1 == '1') && (2 == '2') && (3 == '3')  //=> true

Deep comparison (recursive)

You've probably noticed that this is only shallow comparison tho. Surely Tomáš's solution is "The Right Way™" because it does implicit deep comparison, right ?

Well our arrayCompare procedure is versatile enough to use in a way that makes a deep equality test a breeze …

// isArray :: a -> Bool
const isArray =
  Array.isArray

// arrayDeepCompare :: (a -> a -> Bool) -> [a] -> [a] -> Bool
const arrayDeepCompare = f =>
  arrayCompare (a => b =>
    isArray (a) && isArray (b)
      ? arrayDeepCompare (f) (a) (b)
      : f (a) (b))

const xs = [1,[2,[3]]]
const ys = [1,[2,['3']]]
console.log (arrayDeepCompare (equal) (xs) (ys)) //=> false
// (1 === 1) && (2 === 2) && (3 === 3)           //=> false

console.log (arrayDeepCompare (looseEqual) (xs) (ys)) //=> true
// (1 == 1) && (2 == 2) && (3 == '3')                 //=> true

Simple as that. We build a deep comparator using another higher-order function. This time we're wrapping arrayCompare using a custom comparator that will check if a and b are arrays. If so, reapply arrayDeepCompare otherwise compare a and b to the user-specified comparator (f). This allows us to keep the deep comparison behavior separate from how we actually compare the individual elements. Ie, like the example above shows, we can deep compare using equal, looseEqual, or any other comparator we make.

Because arrayDeepCompare is curried, we can partially apply it like we did in the previous examples too

// arrayDeepEqual :: [a] -> [a] -> Bool
const arrayDeepEqual =
  arrayDeepCompare (equal)

// arrayDeepLooseEqual :: [a] -> [a] -> Bool
const arrayDeepLooseEqual =
  arrayDeepCompare (looseEqual)

To me, this already a clear improvement over Tomáš's solution because I can explicitly choose a shallow or deep comparison for my arrays, as needed.


Object comparison (example)

Now what if you have an array of objects or something ? Maybe you want to consider those arrays as "equal" if each object has the same id value …

// idEqual :: {id: Number} -> {id: Number} -> Bool
const idEqual = x => y =>
  x.id !== undefined && x.id === y.id

// arrayIdEqual :: [a] -> [a] -> Bool
const arrayIdEqual =
  arrayCompare (idEqual)

const xs = [{id:1}, {id:2}]
const ys = [{id:1}, {id:2}]
console.log (arrayIdEqual (xs) (ys)) //=> true
// (1 === 1) && (2 === 2)            //=> true

const zs = [{id:1}, {id:6}]
console.log (arrayIdEqual (xs) (zs)) //=> false
// (1 === 1) && (2 === 6)            //=> false

Simple as that. Here I've used vanilla JS objects, but this type of comparator could work for any object type; even your custom objects. Tomáš's solution would need to be completely reworked to support this kind of equality test

Deep array with objects? Not a problem. We built highly versatile, generic functions, so they'll work in a wide variety of use cases.

const xs = [{id:1}, [{id:2}]]
const ys = [{id:1}, [{id:2}]]
console.log (arrayCompare (idEqual) (xs) (ys))     //=> false
console.log (arrayDeepCompare (idEqual) (xs) (ys)) //=> true

Arbitrary comparison (example)

Or what if you wanted to do some other kind of kind of completely arbitrary comparison ? Maybe I want to know if each x is greater than each y

// gt :: Number -> Number -> Bool
const gt = x => y =>
  x > y

// arrayGt :: [a] -> [a] -> Bool
const arrayGt = arrayCompare (gt)

const xs = [5,10,20]
const ys = [2,4,8]
console.log (arrayGt (xs) (ys))     //=> true
// (5 > 2) && (10 > 4) && (20 > 8)  //=> true

const zs = [6,12,24]
console.log (arrayGt (xs) (zs))     //=> false
// (5 > 6)                          //=> false

Less is More

You can see we're actually doing more with less code. There's nothing complicated about arrayCompare itself and each of the custom comparators we've made have a very simple implementation.

With ease, we can define exactly how we wish for two arrays to be compared — shallow, deep, strict, loose, some object property, or some arbitrary computation, or any combination of these — all using one procedure, arrayCompare. Maybe even dream up a RegExp comparator ! I know how kids love those regexps …

Is it the fastest? Nope. But it probably doesn't need to be either. If speed is the only metric used to measure the quality of our code, a lot of really great code would get thrown away — That's why I'm calling this approach The Practical Way. Or maybe to be more fair, A Practical Way. This description is suitable for this answer because I'm not saying this answer is only practical in comparison to some other answer; it is objectively true. We've attained a high degree of practicality with very little code that's very easy to reason about. No other code can say we haven't earned this description.

Does that make it the "right" solution for you ? That's up for you to decide. And no one else can do that for you; only you know what your needs are. In almost all cases, I value straightforward, practical, and versatile code over clever and fast kind. What you value might differ, so pick what works for you.


Edit

My old answer was more focused on decomposing arrayEqual into tiny procedures. It's an interesting exercise, but not really the best (most practical) way to approach this problem. If you're interested, you can see this revision history.

1 upvote
  flag
Wow, it looks like Lisp. Amazing! – cat
upvote
  flag
+1 for "the best kind of code doesn't even need comments" and your beautiful answer of course. However, I wonder why you decided against Array.prorotype.every. It takes a predicate and the iteration can be stopped early. It is also easy to read provided you know that the passed function has an optional 2nd argument: f => xs => ys => xs.length === ys.length ? xs.every((y, x) => f(x) (ys[y])) : false. I guess the implementation is more memory efficient. It is debatable if this is an idiomatic usage of every though. ys[y] exposes algorithmic details and is less declarative... – ftor
upvote
  flag
@LUH3417 yep, I could've used .every as you described you have you to flip the x and y parameters – xs.every((x,i) => f (x) (ys[i])). I think it's a useful and idiomatic application of .every but I did want to show how to build a generic higher-order procedure from scratch. Also, I know .length and accessing an array element by index (ys[i]) is not very costly in JavaScript, but I wanted to show that it could be done without either of those too. – naomik
upvote
  flag
And yes, I know destructuring the array technical does xs[0], xs.slice(1) but I think it's a safer (and less verbose) pattern than writing your own direct accessors. Thanks for the comment ^_^ – naomik
1 upvote
  flag
"the best kind of code doesn't even need comments" ... hate to say it, but this code could use more of a comment, and/or a different name-- "compare" is pretty vague. If I'm reading correctly, your "compare" is essentially a curried recursive "every". I think. Or is it a curried recursive "some"? Hmm. This is requiring more thinking than necessary. Perhaps a better name would be "arraysEquivalent", leveraging the standard terminology of "equivalence relation". Or, even clearer (to me anyway), "recursivelyEquivalent". – Don Hatch
upvote
  flag
@DonHatch thanks for the opportunity to reply. By "compare" do you mean arrayCompare? Yes the function is curried, but it differs from some and every. arrayCompare takes a comparator and two arrays to compare. I chose a specifically generic name because we can compare arrays using any arbitrary function. The function is curried so it can be specialised to create new array comparison functions (eg, arrayEqual). Can you suggest a better name? What areas do you feel need additional comments or explanation? I'm happy to discuss ^_^ – naomik
upvote
  flag
Right, I meant the "compare" in your arrayCompare. "compare" is unfortunately vague since it is used in lots of differerent ways in other contexts: e.g. the C language's qsort function takes a "compar" functor that returns -1,0, or 1 depending on whether the first arg is less than, equal to, or greater than the second; c++'s std::sort takes a "comp" functor that returns true iff the first arg is less than the second, etc. I think if you used some variant of the word "equivalent" instead, it would make it more immediately clear that the intent is to return a bool expressing equivalence. – Don Hatch
upvote
  flag
Not sure if my point is clear yet-- but my point is, your function isn't really intended to take an arbitrary function, I don't think-- it's intended to take an equivalence relation, and it returns an equivalence relation. That's important-- it wouldn't do anything sensible (I don't think) if given some other kind of arbitrary binary function like the ones I mentioned, even ones that people often call "compare". So I think it would be helpful to put "equivalent" in the name in place of "compare". – Don Hatch
upvote
  flag
Don I understand your point more clearly now. Though I think this is maybe just a JavaScipt naming convention. ===, ==, !=, >, <, etc are called comparison operators in JavaScript. I understand "comparison" used in a different context (eg sorting) can have a different meaning than the way I'm using "compare" here - though I think both are valid – naomik
upvote
  flag
Looking at arrayGt in my answer, I think deriving from (eg) arrayEquivalence would feel wrong because gt (>) is not testing for equivalence - hmm. I still wonder if there's a better name altogether. – naomik
upvote
  flag
Oh! I see, gt does make sense. I missed that at first, even though you included it in your answer, because I didn't read your answer fully, sorry about that. Maybe something like "recursiveEveryBinary" or "recursiveEvery2". Thanks. – Don Hatch
upvote
  flag
your answer is just brilliant. – João Vilaça
upvote
  flag
@ftor, author: super helpful answer, nice work, +1. Feedback: You advocate simplicity, yet no way is an expression with three arrows on one line simple or easy to understand for many developers. For ex: f=> ([x,...xs]) => ([y,...ys]) =>. I constantly use this and still had to mentally decompose it, rather than "just look at it". Second point ftor is right, use every. Even weighing your reasons, on balance it seems better not only to me, but also from your perspective when attempt to infer your design philosophy. – Lee
upvote
  flag
@Lee this curried style is easier to understand with time, but it is just style – This question is specifically about array comparison and not really the place for me to say to curry or not to curry. Writing the function in uncurried form arrayCompare (f, [x,...xs], [y,...xs]) => ... may improve readability for some, but it's just a style difference – the two variants are equivalent when concerning any meaningful factors. Thanks for the comment ^_^ – naomik
upvote
  flag
@Lee, the style in which I write functional programs in JavaScript has changed dramatically over time. This answer was a little stale, so I updated with styles I've been using more recently – naomik
upvote
  flag
I don’t see how currying is just style. It became a thing in math for reasons practical, not aesthetic, it was easier to deal with certain constructs that way, likewise for computer science. continuing comment please wait... – Lee
upvote
  flag
Please don't get hung up on the word style – I'm only concerned with providing an answer that utilizes pure (ie referentially transparent) functions – this can be done using currying, or without. Advantages of one style/technique/theory/rule/pattern over another are not the talking point of this answer. I chose curried style because arrayCompare specializes naturally by accepting a higher order function, but also just because I like curried style ^_^ – naomik
upvote
  flag
...Therefore the objection is, only in cases like these, currying has been reduced to a matter style, possibly being even more difficult for the average programmer. This is conjecture but I feel confident a large majority of devs would say a multiple parameter arrow declaration carries a lower conflictive load in their minds compared to the curried example. It goes beyond the 3 arrows per line, () () feels unusual in javascript, not idiomatic. If the conjecture is correct, it adds a small penalty to the learning curve as new people continually rotate into a code base, style only is ok? – Lee
upvote
  flag
I understand this is a place for learning, but I make an assumption here that the average programmer studying functional style can transform any curried function to an uncurried one. My answer does not make the suggestion that this style is meant to be used in your own program – write it uncurried, write it using your own indentation rules, write it however you want – I write my answers in a style that I believe expresses the program best. I also like to invite others to challenge the way we express our programs syntactically – naomik
upvote
  flag
To be clear I don’t care about style only the advantages of different techniques. I see no concrete benefits here and possible negatives, that’s it. To be truly fair with you i’d have to try it for a while. The teams you work with are a huge factor. I’ve worked on very advanced teams at pure tech companies, but also consulted for corporate america. The difficulty of introducing new things varies widely based on the team in my experience. – Lee
upvote
  flag
To be clear, in this context I consider style and technique to be the same – I don't care about either; I'm only trying to demonstrate a practical, functional approach to the question using a style that I deemed appropriate – naomik
upvote
  flag
Totally fair demonstrate away, and as mentioned you did an excellent job of that. – Lee
upvote
  flag
Lee, we're really missing each other here – I'm not trying to convince you to write curried functions, or not to write them either. My answer is expressed in curried style and uses rather unconventional whitespace, but if that doesn't work for your team, feel free to change the style(s) to whatever you want – I mean, I really don't see a problem unless you're copy/pasting code from SO directly into your program. The answer just shows how the moving parts work – tweak implementation and style to your fancy. I think that applies to all answers on SO, doesn't it? – naomik
upvote
  flag
I hope I’m not communicating negativity or irratitation because that’s not my felling at all. Rather, as we are all here sharing and learning, the intent is just to get the most out of it. If I think I notice a better way of doing something in my mind it’s a guaranteed win, because whether I turn out to be right or wrong, somebody has further learned, improved, sharpened thinking. The matter of ulrmately being right or wrong is not itself a big motivation for me in learning or teaching contexts. – Lee
upvote
  flag
Lee, I don't sense any negativity or irritation. I think the opening sentence of my answer agrees with latter part of your comment. Thanks for the discussion ^_^ – naomik
upvote
  flag
@Lee Currying is an abstraction, namely over arity. The question is thus does abstraction simplify the code? I'd say usually not. Abstraction increases the reader's necessary level of experience to comprehend code, because it hides details. Higher order functions on the other hand offer a wider range of applications than their first order counterparts. They are generalizations. Now with currying you can use specialized instances of a generic function by assigning intermediate functions to variables. So currying may complicate code, but it also includes some nice properties. – ftor
upvote
  flag
Ok cool, I think we are exactly in sync on this discussion point and trade offs. When you say abstraction increases need for experience/comprehension, I assume you mean w.r.t. this subject, and I would agree. It seems a ironic that generally speaking, abstraction often can do the opposite, make things easier to grok and build on. Too bad you don’t live next to the same bar, this stuff could extend to all kinds of interesting tangents over a few beers. :-) – Lee
var er = [{id:"23",name:"23222"}, {id:"222",name:"23222222"}];
var er2 = [{id:"23",name:"23222"}, {id:"222",name:"23222222"}];

var result = (JSON.stringify(er) == JSON.stringify(er2)); // true

It works json objects well if the order of the property of each entry is not changed.

var er = [{name:"23222",id:"23"}, {id:"222",name:"23222222"}];
var er2 = [{id:"23",name:"23222"}, {id:"222",name:"23222222"}];

var result = (JSON.stringify(er) == JSON.stringify(er2)); // false  

But there is only one property or value in each entry of the array, this will work fine.

I came up with another way to do it. Use join('') to change them to string, and then compare 2 strings:

var a1_str = a1.join(''),
    a2_str = a2.join('');

if (a2_str === a1_str) {}
2 upvote
  flag
There's an awful oversight here. [1,2,3,4].join('') === [12,34].join('') // => true – naomik

I would do like this:

[2,3,4,5] == [2,3,4,5].toString()

When you use the "==" operator, javascript check if the values(left and right) is the same type, if it's different javascript try to convert both side in the same type.

Array == String

Array has toString method so javascript use it to convert them to the same type, work the same way writing like this:

[2,3,4,5].toString() == [2,3,4,5].toString()
upvote
  flag
Why downvoted? can you at least explain? – Victor Palomo
upvote
  flag
Because you didn't bother explaining your answer – Green
upvote
  flag
Sorry for the delay, I explained it. – Victor Palomo
2 upvote
  flag
Oversight: [1,2,3,4].toString() === ["1,2,3",4].toString() // => true – naomik
upvote
  flag
It's better to use it when you have only one level of deepness – Victor Palomo

Another approach with very few code (using Array reduce and Array includes):

arr1.length == arr2.length && arr1.reduce((a, b) => a && arr2.includes(b), true)

If you want to compare also the equality of order:

arr1.length == arr2.length && arr1.reduce((a, b, i) => a && arr2[i], true)
  • The length check ensures that the set of elements in one array isn't just a subset of the other one.

  • The reducer is used to walk through one array and search for each item in other array. If one item isn't found the reduce function returns false.

    1. In the first example it's being tested that an element is included
    2. The second example check for the order too
1 upvote
  flag
could you explain a little bit your code to make this answer clearer? – ted
upvote
  flag
1. compare array lengths to make sure that one array isn't a subset of the other one – DEls
upvote
  flag
2. use reducer to walk through one array and search for each item in other array. If one item isn't found the reduce function returns 'false' – DEls
upvote
  flag
@DEls: edited your explanation into the answer (slightly reworded and extended). You may now remove your comments and flag the first comment and this one as obsolete. – try-catch-finally

While the top answer to this question is correct and good, the code provided could use some improvement.

Below is my own code for comparing arrays and objects. The code is short and simple:

Array.prototype.equals = function(otherArray) {
  if (!otherArray || this.length != otherArray.length) return false;
  return this.reduce(function(equal, item, index) {
    var otherItem = otherArray[index];
    var itemType = typeof item, otherItemType = typeof otherItem;
    if (itemType !== otherItemType) return false;
    return equal && (itemType === "object" ? item.equals(otherItem) : item === otherItem);
  }, true);
};

if(!Object.prototype.keys) {
  Object.prototype.keys = function() {
    var a = [];
    for (var key in this) {
      if (this.hasOwnProperty(key)) a.push(key);
    }
    return a;
  }
  Object.defineProperty(Object.prototype, "keys", {enumerable: false});
}

Object.prototype.equals = function(otherObject) {
  if (!otherObject) return false;
  var object = this, objectKeys = object.keys();
  if (!objectKeys.equals(otherObject.keys())) return false;
  return objectKeys.reduce(function(equal, key) {
    var value = object[key], otherValue = otherObject[key];
    var valueType = typeof value, otherValueType = typeof otherValue;
    if (valueType !== otherValueType) return false;
    // this will call Array.prototype.equals for arrays and Object.prototype.equals for objects
    return equal && (valueType === "object" ? value.equals(otherValue) : value === otherValue);
  }, true);
}
Object.defineProperty(Object.prototype, "equals", {enumerable: false});

This code supports arrays nested in objects and objects nested in arrays.

You can see a full suite of tests and test the code yourself at this repl: https://repl.it/Esfz/3

If they are two arrays of numbers or strings only, this is a quick one-line one

const array1 = [1, 2, 3];
const array2 = [1, 3, 4];
console.log(array1.join(',') === array2.join(',')) //false

const array3 = [1, 2, 3];
const array4 = [1, 2, 3];
console.log(array3.join(',') === array4.join(',')) //true
upvote
  flag
const array1 = [1]; const array2 = [1, 1]; console.log(array1.join('') === array2.join('')) //returns true – Dan M.
upvote
  flag
it shouldn't: array1.join('') is '1' and array2.join('') is '11' – Gaizka Allende
upvote
  flag
sorry, typo. The first array should be [11]. Pretty obvious as to why this happens and how to fix. – Dan M.
upvote
  flag
Not sure what you're about, it's pretty simple: [1].join() is "1" and [1,1].join() is "1,1", so they'll never be equal – Gaizka Allende
upvote
  flag
please, read my comment again more carefully. If you still don't see it, please take a loot at ideone.com/KFu427 – Dan M.
upvote
  flag
const a1 = [1, 1, 21]; const a2 = [11, 21]; console.log(a1.join('') === a2.join('')) // returns true. The given solution would work only for array consisting of single digits. – Richie
upvote
  flag
that's right!! :)) just add a character to the join method const array1 = [1, 1, 21]; const array1 = [11, 21]; console.log(array7.join(',') === array8.join(',')) //false – Gaizka Allende
upvote
  flag
Fails for [1,2] and ["1,2"]. – try-catch-finally

In the spirit of the original question:

I'd like to compare two arrays... ideally, efficiently. Nothing fancy, just true if they are identical, and false if not.

I have been running performance tests on some of the more simple suggestions proposed here with the following results (fast to slow):

while (67%) by Tim Down

var i = a1.length;
while (i--) {
    if (a1[i] !== a2[i]) return false;
}
return true

every (69%) by user2782196

a1.every((v,i)=> v === a2[i]);

reduce (74%) by DEIs

a1.reduce((a, b) => a && a2.includes(b), true);

join & toString (78%) by Gaizka Allende & vivek

a1.join('') === a2.join('');

a1.toString() === a2.toString();

half toString (90%) by Victor Palomo

a1 == a2.toString();

stringify (100%) by radtek

JSON.stringify(a1) === JSON.stringify(a2);

Note the examples below assumes the arrays are sorted, single-dimensional arrays. .length comparison has been removed for a common benchmark (add a1.length === a2.length to any of the suggestions and you will get a ~10% performance boost). Choose whatever solutions that works best for you knowing the speed and limitation of each.

Unrelated note: it is interesting to see people getting all trigger-happy John Waynes on the down vote button on perfectly legitimate answers to this question.

This compares 2 unsorted arrays:

function areEqual(a, b) {
  if ( a.length != b.length) {
    return false;
  }
  return a.filter(function(i) {
    return !b.includes(i);
  }).length === 0;  
}
var a1 = [1,2,3,6];
var a2 = [1,2,3,5];

function check(a, b) {
  return (a.length != b.length) ? false : 
  a.every(function(row, index) {
    return a[index] == b[index];
  });
}  

check(a1, a2);

////// OR ///////

var a1 = [1,2,3,6];
var a2 = [1,2,3,6];

function check(a, b) {
  return (a.length != b.length) ? false : 
  !(a.some(function(row, index) {
    return a[index] != b[index];
  }));
}  

check(a1, a2)
upvote
  flag
You can you some function as well which will not iterate completely if we get the required condition satisfied, like above – Vasanth

tried deep-equal and it worked

var eq = require('deep-equal');
eq({a: 1, b: 2, c: [3, 4]}, {c: [3, 4], a: 1, b: 2});

Choose each from [a] and loop through all from [b]: Result: 1, 5

var a = [1,4,5,9];
var b = [1,6,7,5];

for (i = 0; i < a.length; i++) {
    for (z = 0; z < a.length; z++) {
        if (a[i] === b[z]) {
            console.log(b[z]); // if match > console.log it 
        }
    }
}

I have used : to join array and create a string to compare. for scenarios complex than this example you can use some other separator.

var a1 = [1,2,3];
var a2 = [1,2,3];
if (a1.length !== a2.length) {
   console.log('a1 and a2 are not equal')
}else if(a1.join(':') === a2.join(':')){
   console.log('a1 and a2 are equal')
}else{
   console.log('a1 and a2 are not equal')
}
function palindrome(text) 
{
    var Res1 = new Array();
    var Res2 = new Array();
    for (i = 0; i < text.length; i++) 
    {  
            Res1[i] = text.substr(i, 1);        
    } 

    j=0;
for (k = (text.length-1); k>=0; k--) 
    {  
            Res2[j] = text.substr(k, 1);    
            j=j+1;  
    }       

    if(JSON.stringify(Res1)==JSON.stringify(Res2)){
        return true;
    }else{
        return false;
    }
}

document.write(palindrome("katak"));

Even though this has a lot of answers, one that I believe to be of help:

const newArray = [ ...new Set( [...arr1, ...arr2] ) ]

It is not stated in the question how the structure of the array is going to look like, so If you know for sure that you won't have nested arrays nor objects in you array (it happened to me, that's why I came to this answer) the above code will work.

What happens is that we use spread operator ( ... ) to concat both arrays, then we use Set to eliminate any duplicates. Once you have that you can compare their sizes, if all three arrays have the same size you are good to go.

This answer also ignores the order of elements, as I said, the exact situation happened to me, so maybe someone in the same situation might end up here (as I did).


Edit1.

Answering Dmitry Grinko's question: "Why did you use spread operator ( ... ) here - ...new Set ? It doesn't work"

Consider this code:

const arr1 = [ 'a', 'b' ]
const arr2 = [ 'a', 'b', 'c' ]
const newArray = [ new Set( [...arr1, ...arr2] ) ]
console.log(newArray)

You'll get

[ Set { 'a', 'b', 'c' } ]

In order to work with that value you'd need to use some Set properties (see https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set). On the other hand, when you use this code:

const arr1 = [ 'a', 'b' ]
const arr2 = [ 'a', 'b', 'c' ]
const newArray = [ ...new Set( [...arr1, ...arr2] ) ]
console.log(newArray)

You'll get

[ 'a', 'b', 'c' ]

That's the difference, the former would give me a Set, it would work too as I could get the size of that Set, but the latter gives me the array I need, what's more direct to the resolution.

upvote
  flag
Why did you use spread operator ( ... ) here - ...new Set ? It doesn't work. – Dmitry Grinko
upvote
  flag
Dmitry Grinko I believe I answered your question on my Edit1. But I'm not sure what you meant by saying 'it doesn't work', as both answers can get you in the way – Jeferson Euclides
1 upvote
  flag
brilliant! .... – Toolkit

A simple approach:

function equals(a, b) {
    if ((a && !b) || (!a && b) || (!a && !b) || (a.length !== b.length)) {
        return false;
    }

    var isDifferent = a.some(function (element, index) { 
        return element !== b[index];
    });

    return !isDifferent;
}
JSON.stringify(collectionNames).includes(JSON.stringify(sourceNames)) ?  array.push(collection[i]) : null

This is how i did it.

upvote
  flag
Good solution - but I wonder in certain situations if it will not always work as intended, such as with certain primitives or deeply nested arrays? I hope it works in all circumstances though – Ben Rondeau
upvote
  flag
I'm not sure if it works in nested arrays. – Leed

Comparing 2 arrays:

var arr1 = [1,2,3];
var arr2 = [1,2,3];

function compare(arr1,arr2)
{
  if((arr1 === arr2) && (arr1.length == arr2.length))
    return true;
  else
    return false;
}

calling function

var isBool = compare(arr1.sort().join(),arr2.sort().join());

Not the answer you're looking for? Browse other questions tagged or ask your own question.