By Julian H. Lam


2011-10-20 14:27:57 8 Comments

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?

30 comments

@ArifMustafa 2019-07-16 06:23:08

I believe in plain JS and with ECMAScript 2015, which is sweet and simple to understand.

var is_arrays_compare_similar = function (array1, array2) {

    let flag = true;

    if (array1.length == array2.length) {

        // check first array1 object is available in array2 index
        array1.every( array_obj => {
            if (flag) {
                if (!array2.includes(array_obj)) {
                    flag = false;
                }
            }
        });

        // then vice versa check array2 object is available in array1 index
        array2.every( array_obj => {
            if (flag) {
                if (!array1.includes(array_obj)) {
                    flag = false;
                }
            }
        });

        return flag;
    } else {
        return false;
    }

}

hope it will help someone.

@Prany 2019-08-08 15:52:09

thanks , it did :)

@Pedro Bustamante 2019-06-28 10:54:53

In a simple way uning stringify but at same time thinking in complex arrays:

**Simple arrays**:  
var a = [1,2,3,4];  
var b = [4,2,1,4];  
JSON.stringify(a.sort()) === JSON.stringify(b.sort()) // true  

**Complex arrays**:  
var a = [{id:5,name:'as'},{id:2,name:'bes'}];  
var b = [{id:2,name:'bes'},{id:5,name:'as'}];  
JSON.stringify(a.sort(function(a,b) {return a.id - b.id})) === JSON.stringify(b.sort(function(a,b) {return a.id - b.id})) // true  

**Or we can create a sort function**  

function sortX(a,b) {  
return a.id -b.id; //change for the necessary rules  
}  
JSON.stringify(a.sort(sortX)) === JSON.stringify(b.sort(sortX)) // true  

@durga patra 2019-06-24 14:58:25

Your code will not handle the case appropriately when both arrays have same elements but not in same order.

Have a look at my code with your example which compares two arrays whose elements are numbers, you might modify or extend it for other element types (by utilising .join() instead of .toString()).

var a1 = [1,2,3];
var a2 = [1,2,3];
const arraysAreEqual = a1.sort().toString()==a2.sort().toString();
// true if both arrays have same elements else false
console.log(arraysAreEqual);

@corysimmons 2019-06-02 02:33:42

Actually, in the Lodash documentation, they give two pretty good examples for comparing and return fresh arrays for both differences and similarities (respectively in the examples below):

import { differenceWith, intersectionWith, isEqual } from 'lodash'

differenceWith(
  [{ a: 1 }, { b: 1 }],
  [{ a: 1 }, { b: 1 }, { c: 1 }],
  isEqual
) // []... 💀the bigger array needs to go first!

differenceWith(
  [{ a: 1 }, { b: 1 }, { c: 1 }],
  [{ a: 1 }, { b: 1 }],
  isEqual,
) // [{ c: 1 }] 🎉

intersectionWith(
  [{ a: 1 }, { b: 1 }],
  [{ a: 1 }, { b: 1 }, { c: 1 }],
  isEqual,
) // [{ a: 1 }, { b: 1 }] 🎉this one doesn't care about which is bigger

If you won't always know which array will be bigger, you can write a helper function for it like so:

const biggerFirst = (arr1, arr2) => {
  return arr1.length > arr2.length ? [arr1, arr2] : [arr2, arr1]
}

const [big, small] = biggerFirst(
  [{ a: 1 }, { b: 1 }],
  [{ a: 1 }, { b: 1 }, { c: 1 }],
)

differenceWith(big, small, isEqual) // 🎉even though we have no idea which is bigger when they are fed to biggerFirst()

From what I can tell, these match deeply as well so that's pretty nice.

I know relying on libraries for everything shouldn't be applauded, but this is the most concise/clean solution I've found to a really common problem. Hope it helps someone!

@Daphoque 2019-05-21 08:50:39

Récursive cmp function working with number/string/array/object

<script>
var cmp = function(element, target){

   if(typeof element !== typeof target)
   {
      return false;
   }
   else if(typeof element === "object" && (!target || !element))
   {
      return target === element;
   }
   else if(typeof element === "object")
   {
       var keys_element = Object.keys(element);
       var keys_target  = Object.keys(target);
       
       if(keys_element.length !== keys_target.length)
       {
           return false;
       }
       else
       {
           for(var i = 0; i < keys_element.length; i++)
           {
                if(keys_element[i] !== keys_target[i])
                    return false;
                if(!cmp(element[keys_element[i]], target[keys_target[i]]))
                    return false;
           }
		   return true;
       }
   }
   else
   {
   	   return element === target;

   }
};

console.log(cmp({
    key1: 3,
    key2: "string",
    key3: [4, "45", {key4: [5, "6", false, null, {v:1}]}]
}, {
    key1: 3,
    key2: "string",
    key3: [4, "45", {key4: [5, "6", false, null, {v:1}]}]
})); // true

console.log(cmp({
    key1: 3,
    key2: "string",
    key3: [4, "45", {key4: [5, "6", false, null, {v:1}]}]
}, {
    key1: 3,
    key2: "string",
    key3: [4, "45", {key4: [5, "6", undefined, null, {v:1}]}]
})); // false
</script>

@Cels 2019-01-25 09:27:28

Here is a very short way to do it

function arrEquals(arr1, arr2){
     return arr1.length == arr2.length && 
     arr1.filter(elt=>arr1.filter(e=>e===elt).length == arr2.filter(e=>e===elt).length).length == arr1.length
}

@CodeIntern 2019-04-25 22:51:09

Wouldn't this fail with [2, 2, 3] and [3, 3, 2]?

@Cels 2019-05-18 21:24:36

I've edited my answer, CodeIntern. Thanks for the feedback

@Esqarrouth 2018-10-07 16:38:40

Here is a Typescript version:

//https://stackoverflow.com/a/16436975/2589276
export function arraysEqual<T>(a: Array<T>, b: Array<T>): boolean {
    if (a === b) return true
    if (a == null || b == null) return false
    if (a.length != b.length) return false

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

//https://stackoverflow.com/a/16436975/2589276
export function arraysDeepEqual<T>(a: Array<T>, b: Array<T>): boolean {
    return JSON.stringify(a) === JSON.stringify(b)
}

Some test cases for mocha:

it('arraysEqual', function () {
    let a = [1,2]
    let b = [1,2]
    let c = [2,3]
    let d = [2, 3]
    let e = ['car','apple','banana']
    let f = ['car','apple','banana']
    let g = ['car','apple','banan8']

    expect(arraysEqual(a, b)).to.equal(true)
    expect(arraysEqual(c, d)).to.equal(true)
    expect(arraysEqual(a, d)).to.equal(false)
    expect(arraysEqual(e, f)).to.equal(true)
    expect(arraysEqual(f, g)).to.equal(false)
})

it('arraysDeepEqual', function () {
    let a = [1,2]
    let b = [1,2]
    let c = [2,3]
    let d = [2, 3]
    let e = ['car','apple','banana']
    let f = ['car','apple','banana']
    let g = ['car','apple','banan8']
    let h = [[1,2],'apple','banan8']
    let i = [[1,2],'apple','banan8']
    let j = [[1,3],'apple','banan8']

    expect(arraysDeepEqual(a, b)).to.equal(true)
    expect(arraysDeepEqual(c, d)).to.equal(true)
    expect(arraysDeepEqual(a, d)).to.equal(false)
    expect(arraysDeepEqual(e, f)).to.equal(true)
    expect(arraysDeepEqual(f, g)).to.equal(false)
    expect(arraysDeepEqual(h, i)).to.equal(true)
    expect(arraysDeepEqual(h, j)).to.equal(false)
})

@Vitalii Shevchuk 2018-09-27 09:57:05

Only works for one level Arrays, String or Numbers type

 function isArrayEqual(ar1, ar2) {
     return !ar1.some(item => ar2.indexOf(item) === -1) && ar1.length === ar2.length;
 }

@William Roque 2018-08-19 20:59:52

I quite like this approach in that it is substantially more succinct than others. It essentially contrasts all items to an accumulator which maintains a same value which is replaced with NaN if it reaches one that is distinct. As NaN cannot be equal to any value, including NaN itself, the value would be converted into a boolean (!!) and be false. Otherwise, the value should be true. To prevent an array of zeros to return false, the expression is converted to its absolute value and added to 1, thus !!(Math.abs(0) + 1) would be true. The absolute value was added for the case -1, which, when added to 1 would be equal to 0 and so, false.

function areArrayItemsEqual(arr) {
    return !!(Math.abs(arr.reduce((a, b) => a === b ? b : NaN)) + 1);
}

@user2782196 2013-11-02 20:56:04

While this only works for scalar arrays (see note below), it is short:

array1.length === array2.length && array1.every(function(value, index) { return value === array2[index]})

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

array1.length === array2.length && array1.every((value, index) => value === array2[index])

(Note: 'scalar' here means values that can be compared directly using === . So: numbers, strings, objects by reference, functions by reference. See the MDN reference for more info about the comparison operators).

UPDATE

From what I read from the comments, sorting the array and comparing may give accurate result:

array1.length === array2.length && array1.sort().every(function(value, index) { return value === array2.sort()[index]});

Eg:

array1 = [2,3,1,4];
array2 = [1,2,3,4];

Then the above code would give true

@Ellen Spertus 2013-12-15 15:05:23

I like this, although readers should be aware this only works on sorted arrays.

@Michał Miszczyszyn 2016-03-24 14:03:56

It works on any kind of arrays, sorted or not @espertus

@Ellen Spertus 2016-03-25 20:13:02

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

@Michał Miszczyszyn 2016-03-26 00:39:02

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.

@Quentin Roy 2016-06-06 03:25:32

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

@mems 2016-11-21 15:25:22

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)

@Govind Rai 2017-01-07 00:36:58

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

@Slava Fomin II 2018-11-14 10:55:21

You should not sort the second array for every element of the first one. Sort them both in the beginning of the function execution. Or, even better, add a function parameter to determine if sorting is required. Also, there is no meaning in organizing all code into a single line, it's hard to read.

@Slava Fomin II 2018-11-14 10:59:21

Also, calling the sort() method will mutate the original array, which is almost never a good thing. You should clone it beforehand.

@Petroff 2019-01-23 10:41:26

It's not good practice to use sort inside loop. Just sort the arrays once before the comparison instead of doing it at every single iteration.

@Fabian von Ellerts 2019-02-14 09:56:20

@mems You might as well update the answer, your code is even faster: jsben.ch/iqfgt

@Anatolii Parubets 2019-08-08 13:24:18

Thank for solution

@J.M.I. MADISON 2018-06-27 07:58:18

Works with MULTIPLE arguments with NESTED arrays:

//:Return true if all of the arrays equal.
//:Works with nested arrays.
function AllArrEQ(...arrays){
    for(var i = 0; i < (arrays.length-1); i++ ){
        var a1 = arrays[i+0];
        var a2 = arrays[i+1];
        var res =( 
            //:Are both elements arrays?
            Array.isArray(a1)&&Array.isArray(a2) 
            ?
            //:Yes: Compare Each Sub-Array:
            //:v==a1[i]
            a1.every((v,i)=>(AllArrEQ(v,a2[i])))
            :
            //:No: Simple Comparison:
            (a1===a2)
        );;
        if(!res){return false;}
    };;
    return( true );
};;

console.log( AllArrEQ( 
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
        [1,2,3,[4,5,[6,"ALL_EQUAL"   ]]],
));; 

@J.M.I. MADISON 2018-06-27 07:28:56

Recursive & works on NESTED arrays:

function ArrEQ(a1,a2){
   return( 
        //:Are both elements arrays?
        Array.isArray(a1)&&Array.isArray(a2) 
        ?
        //:Yes: Test each entry for equality:
        a1.every((v,i)=>(ArrEQ(v,a2[i])))
        :
        //:No: Simple Comparison:
        (a1===a2)
   );;
};;

console.log( "Works With Nested Arrays:" );
console.log( ArrEQ( 
    [1,2,3,[4,5,[6,"SAME/IDENTICAL"]]],
    [1,2,3,[4,5,[6,"SAME/IDENTICAL"]]]
));;     
console.log( ArrEQ( 
    [1,2,3,[4,5,[6,"DIFFERENT:APPLES" ]]],
    [1,2,3,[4,5,[6,"DIFFERENT:ORANGES"]]]
));;  

@Lacho Tomov 2018-03-21 15:58:30

With an option to compare the order or not:

function arraysEqual(a1, a2, compareOrder) {
    if (a1.length !== a2.length) {
        return false;
    }

    return a1.every(function(value, index) {
        if (compareOrder) {
            return value === a2[index];
        } else {
            return a2.indexOf(value) > -1;
        }
    });
}

@AL-zami 2018-05-12 12:05:06

Already some great answers.But i would like to share anther idea which has proven to be reliable in comparing arrays. We can compare two array using JSON.stringify ( ) . It will create a string out the the array and thus compare two obtained strings from two array for equality

JSON.stringify([1,{a:1},2]) == JSON.stringify([1,{a:1},2]) //true

JSON.stringify([1,{a:1},2]) == JSON.stringify([1,{a:2},2]) //false

JSON.stringify([1,{a:1},2]) == JSON.stringify([1,{a:2},[3,4],2]) //false

JSON.stringify([1,{a:1},[3,4],2]) == JSON.stringify([1,{a:2},[3,4],2]) //false

JSON.stringify([1,{a:2},[3,4],2]) == JSON.stringify([1,{a:2},[3,4],2]) //true

JSON.stringify([1,{a:2},[3,4],2]) == JSON.stringify([1,{a:2},[3,4,[5]],2]) //false

JSON.stringify([1,{a:2},[3,4,[4]],2]) == JSON.stringify([1,{a:2},[3,4,[5]],2]) //false

JSON.stringify([1,{a:2},[3,4,[5]],2]) == JSON.stringify([1,{a:2},[3,4,[5]],2]) //true

@user633183 2015-12-13 22:10:55

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.

@user6445533 2016-08-15 18:46:11

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

@user633183 2016-08-15 19:21:25

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

@user633183 2016-08-15 19:24:01

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 ^_^

@Don Hatch 2017-05-10 01:09:07

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

@user633183 2017-05-10 01:14:09

@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 ^_^

@Don Hatch 2017-05-10 01:19:43

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 2017-05-10 01:29:32

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

@user633183 2017-05-10 01:50:46

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

@user633183 2017-05-10 01:59:55

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.

@Don Hatch 2017-05-10 02:35:37

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.

@whitneyland 2017-11-22 20:18:35

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

@user633183 2017-11-22 20:37:21

@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 ^_^

@user633183 2017-11-22 20:56:59

@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

@whitneyland 2017-11-22 23:19:08

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

@user633183 2017-11-22 23:26:00

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 ^_^

@whitneyland 2017-11-22 23:31:17

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

@user633183 2017-11-22 23:36:05

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

@whitneyland 2017-11-22 23:37:05

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.

@user633183 2017-11-22 23:42:02

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

@user633183 2017-11-22 23:48:00

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?

@whitneyland 2017-11-23 00:05:13

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.

@user633183 2017-11-23 03:47:11

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 ^_^

@user6445533 2017-11-23 12:40:08

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

@whitneyland 2017-11-23 14:57:45

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. :-)

@bucabay 2018-10-06 09:15:19

Really great approach and I agree the reusability is great (even if out of scope of the question). The complexity is high even in 2018 when ES6 syntax and functional approach is well understood. The hardest part to grok is that it uses destructing and recursion for array iteration. Thus you have the side-effect x === undefined && y === undefined which requires you to read backwards to get then it is required to ensure both array iterations yield undefined which means they are of equal length. A length check hidden in the pattern used does require comments.

@G. Stoynev 2019-08-06 11:33:20

@user633183, great answer, but the fact that a large percentage of your comments here are to defend your choice of "style" actually works against the very thing you're trying to defend.I think your choice of "style" is preposterous from the point of view of SO's purpose. It's a little like "Do you have the time?" "Let me show you how to build a clock"

@Amay Kulkarni 2018-01-15 14:27:51

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

@Michael Yang 2018-02-27 04:20:27

This answer won't work, as the === doesn't behave as expected for arrays.

@Amay Kulkarni 2018-02-28 14:14:27

The answer works, although === does not have any significance here(since sort() works on array only). Even == will also work.

@Michael Yang 2018-03-03 20:32:39

Try it out yourself; it prints false if you run this code. This is because of the comparison of the arrays' reference values by both == and === instead of their actual values. The == and === are intended only for primitive type comparison.

@Amay Kulkarni 2018-03-13 10:12:36

It returns true, we have used it, but i have removed '===' now as it is not necassary

@Michael Yang 2018-03-20 06:52:51

Ah, I did not notice you were converting to a string and calling the function after sorting and joining; my apologizes.

@Tomáš Zato 2013-02-13 12:49:05

To compare arrays, loop through them and compare every value:

Comparing arrays:

// 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/

@Julian H. Lam 2013-02-13 16:05:34

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"!

@Tim S. 2013-05-15 13:19:14

If you want to do strict comparisons use this[i] !== array[i] instead of !=.

@Oliver 2013-05-31 12:24:52

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.

@Igor S. 2013-06-05 15:38:32

It fails on comparing arrays with the same values but different order. Please check my suggestion stackoverflow.com/a/16944097/1494393

@Luca Fagioli 2013-06-07 12:39:40

+1 for the answer and a beer to your health for writing the function in the array prototype.

@Pete 2013-09-19 10:34:45

Nice answer... but shouldn't you be caching the array length for the loop: for (var i = 0, len = this.length; i < len; i++)

@Tolga E 2013-10-16 19:30:46

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

@B T 2013-10-25 02:53:06

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

@harmstyler 2013-12-10 19:30:19

This works great! However, I needed to compare arrays of objects. I used JSON.stringify(Object) for the comparison. gist.github.com/harmstyler/7896595

@Tomáš Zato 2013-12-10 23:19:51

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 2013-12-11 00:30:44

@WillshawMedia oh, you're right!

@cookie monster 2014-01-01 17:46:39

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.

@Tomáš Zato 2014-01-02 09:04:00

And would it still have a method .compare?

@Pinocchio 2014-04-06 22:43:15

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.

@Tomáš Zato 2014-04-08 08:19:01

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.

@Johnride 2014-04-11 18:13:20

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.

@Flash Thunder 2014-05-29 04:16:08

To be honest, this function is damn too slow when you need to compare it quick (for example in mousemove event)...

@Tomáš Zato 2014-05-29 13:09:42

And which is faster?

@Olivier Pons 2014-06-02 16:12:44

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.

@Tomáš Zato 2014-06-02 18:20:02

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)

@Jasper 2014-08-14 09:29:20

Changing a built-in type's prototype is definitely not the right way

@Tomáš Zato 2014-08-14 11:59:29

@Jasper Array.equals is not a built-in prototype according to ECMAScript specs. Please check your sources again.

@Jasper 2014-08-14 12:38:16

@TomášZato Yes, but Array is. The point is, that since Array is a built-in, you shouldn't modify its prototype.

@Tomáš Zato 2014-08-14 13:46:52

@Jasper Why not? Anyway, you can easily rewrite my function to a procedural version, instead of the OOP one.

@Jasper 2014-09-01 08:38:10

@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 2014-09-01 09:07:15

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"

@firstdoit 2015-01-09 12:12:12

I made a non-prototypal version of your array equals function here: stackoverflow.com/questions/27852356/…

@Piyush Dholariya 2015-01-21 12:19:37

I really appreciate you to give such this effort to give your input. salute u

@Robert Sim 2015-04-06 11:25:05

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

@Tomáš Zato 2015-04-06 15:34:45

@RobertSim And to be completelly correct, you could raise a warning in the console :)

@Robert Sim 2015-04-07 02:27:37

@TomášZato ah. i didn't think of that. I have been working on short term projects to consider the warnings. thanks. :)

@Jasper 2015-04-07 09:03:02

@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 2015-04-07 09:09:15

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 2015-04-07 09:11:33

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

@tne 2015-05-06 11:11:46

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

@Tomáš Zato 2015-05-06 11:22:38

@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 2015-05-06 11:25:06

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

@tne 2015-05-06 11:40:28

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

@Tomáš Zato 2015-05-06 11:56:46

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

@tne 2015-05-06 12:28:25

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

@Jasper 2015-05-06 13:36:14

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

@Tomáš Zato 2015-05-06 13:43:33

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

@Jasper 2015-05-06 13:56:38

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

@Stevanicus 2015-05-18 07:40:43

@TomášZato thanks for the answer, inspired me to write a similar solution for a future release for firebrickjs

@dievardump 2015-09-29 15:20:45

Your Array.ptototype.equals should use a strict comparaison. Else things like [[]].equals([false]); will return true.

@Tomáš Zato 2015-09-29 15:30:59

@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?

@dievardump 2015-09-29 15:58:43

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

@Tomáš Zato 2015-09-29 16:06:10

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

@Samy Bencherif 2016-03-07 02:07:29

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

@Kade Hafen 2016-12-20 23:15:15

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.

@Otvazhnii 2017-04-19 09:40:35

Seems like great. But if arrays have same values in different orders, it returns false. This should be corrected, cause this is very important.

@Tomáš Zato 2017-04-19 10:57:28

@MrEvgenyShcherbina This is intended. You have to sort the arrays if you want to compare them regardless of order of values.

@rigdonmr 2017-08-10 20:34:43

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.

@Emobe 2019-03-13 10:49:38

@rigdonmr apparently you'll need your own language too as the Array prototype is being modified

@Victor 2019-05-06 17:45:48

Very nice! Perfect!

@Leed 2017-11-24 18:36:29

JSON.stringify(collectionNames).includes(JSON.stringify(sourceNames)) ?  array.push(collection[i]) : null

This is how i did it.

@Ben Rondeau 2017-12-13 21:37:28

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

@Leed 2017-12-14 00:47:33

I'm not sure if it works in nested arrays.

@Pedro Rodrigues 2017-11-19 14:29:24

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

@Jeferson Euclides 2017-11-07 13:04:30

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.

@Dmitry Grinko 2017-11-09 19:34:18

Why did you use spread operator ( ... ) here - ...new Set ? It doesn't work.

@Jeferson Euclides 2017-11-10 11:37:34

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

@Luhut Sihombing 2017-11-06 10:03:27

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

@Jason Boerner 2014-02-03 14:20:53

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

@Vitaliy Alekask 2015-08-18 13:23:50

Note that order matters _.isEqual([1,2,3], [2,1,3]) => false

@hellatan 2016-02-18 15:36:28

or if you want just the isEqual functionality, you can always use the lodash.isequal module

@Ronan Quillevere 2017-03-31 15:00:10

You can maybe use _.difference(); if order does not matter to you

@Filype 2017-06-02 11:30:25

We can sort the array before this check if the order doesnt matter _.isEqual([1,2,3].sort(), [2,1,3].sort()) => true

@Manoj Yadav 2017-09-04 21:09:15

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')
}

@DEls 2016-11-08 21:39:52

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

@ted 2016-11-08 22:04:32

could you explain a little bit your code to make this answer clearer?

@DEls 2016-11-09 16:29:52

1. compare array lengths to make sure that one array isn't a subset of the other one

@DEls 2016-11-09 16:31:03

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'

@try-catch-finally 2017-07-15 08:26:24

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

@Gaizka Allende 2017-02-09 17:23:48

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

@Dan M. 2017-05-07 17:58:41

const array1 = [1]; const array2 = [1, 1]; console.log(array1.join('') === array2.join('')) //returns true

@Gaizka Allende 2017-05-09 05:27:26

it shouldn't: array1.join('') is '1' and array2.join('') is '11'

@Dan M. 2017-05-10 02:21:50

sorry, typo. The first array should be [11]. Pretty obvious as to why this happens and how to fix.

@Gaizka Allende 2017-05-11 15:01:53

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

@Dan M. 2017-05-11 15:24:08

please, read my comment again more carefully. If you still don't see it, please take a loot at ideone.com/KFu427

@Richie 2017-06-10 03:59:55

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.

@Gaizka Allende 2017-06-12 11:47:43

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

@try-catch-finally 2017-07-15 08:43:35

Fails for [1,2] and ["1,2"].

@Gaizka Allende 2018-11-09 18:17:36

true but that is really out of question

@jclobro 2017-06-07 15:45:41

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 
        }
    }
}

@d9k 2017-05-24 15:11:38

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

@radtek 2014-05-09 02:38:11

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.

@Pardeep Jain 2016-01-17 19:03:27

good answer but why []==[] return false ? both are simple objects then why ?

@radtek 2016-01-17 19:52:52

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

@Lukas 2017-04-29 11:03:41

just to note that JSON stringify function is not quick. Used with larger arrays will definitely introduce lag.

@Don Hatch 2017-05-10 01:02:39

The question specifically asks whether there is a better/faster way than using JSON.stringify.

@radtek 2017-05-11 21:30:46

It gets into more detail on why this may be a good solution for some situations.

@radtek 2017-09-08 18:23:29

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.

@hqzxzwb 2019-01-11 15:21:09

This will crash when there is circular reference.

@Mars Robertson 2019-03-02 13:52:56

Honestly, I did not notice at first that original question mentions JSON.stringify() - for simple use cases it feels the easiest one...

@Vasanth 2017-03-08 14:40:02

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)

@Vasanth 2017-03-08 14:42:11

You can you some function as well which will not iterate completely if we get the required condition satisfied, like above

@Nathan Boolean Trujillo 2017-03-01 21:28:16

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

Related Questions

Sponsored Content

39 Answered Questions

[SOLVED] Loop through an array in JavaScript

46 Answered Questions

3 Answered Questions

27 Answered Questions

[SOLVED] What does "use strict" do in JavaScript, and what is the reasoning behind it?

57 Answered Questions

[SOLVED] How do I include a JavaScript file in another JavaScript file?

79 Answered Questions

[SOLVED] How do I remove a particular element from an array in JavaScript?

  • 2011-04-23 22:17:18
  • Walker
  • 5894644 View
  • 7352 Score
  • 79 Answer
  • Tags:   javascript arrays

30 Answered Questions

[SOLVED] How to append something to an array?

38 Answered Questions

[SOLVED] How do I remove a property from a JavaScript object?

86 Answered Questions

[SOLVED] How do JavaScript closures work?

33 Answered Questions

[SOLVED] For-each over an array in JavaScript?

Sponsored Content