14

I am having two arrays, how can i compare the two arrays at single shot.

   var arr1= ["a","b","c"];
   var arr2 = ["a","c","d"]

   if(arr1 == arr2){
      console.log(true);
    }else{
      console.log(false);
    }
gauti
  • 1,264
  • 3
  • 17
  • 43
  • Possible duplicate of [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – ibodi Jun 10 '19 at 00:17

8 Answers8

23
var arr1 = ["a","b","c"];
var arr2 = ["a","c","d"];

if (arr1.length == arr2.length
    && arr1.every(function(u, i) {
        return u === arr2[i];
    })
) {
   console.log(true);
} else {
   console.log(false);
}

Side note for edge cases:

=== is often considered slightly broken for this kind of task because NaN behaves unexpectedly:

var arr1 = ["a",NaN,"b"];
var arr2 = ["a",NaN,"b"];

if (arr1.length == arr2.length
    && arr1.every(function(u, i) {
        return u === arr2[i];
    })
) {
   console.log(true);
} else {
   console.log(false);
}

The code above actually logs false because NaN !== NaN. In addition, === can't distinguish +0 from -0. To cover both of these cases, you could use a stronger comparison known as "egal" or "is", which can easily be implemented like so:

function is(a, b) {
    return a === b && (a !== 0 || 1 / a === 1 / b) // false for +0 vs -0
        || a !== a && b !== b; // true for NaN vs NaN
}

var arr1 = ["a",NaN,"b"];
var arr2 = ["a",NaN,"b"];

if (arr1.length == arr2.length
    && arr1.every(function(u, i) {
        // Use "is" instead of "==="
        return is(u, arr2[i]);
    })
) {
   console.log(true);
} else {
   console.log(false);
}
Nathan Wall
  • 10,530
  • 4
  • 24
  • 47
  • 1
    Note that this might give the wrong results in case arr1 is shorter then arr2 - try: `var arr1 = [ 'a', 'b' ], arr2 = ['a','b','c'];` Include a simple length comparison before the every, and you're done: `if( arr1.length === arr2.length && arr1.every( ...` – Erwin Wessels Mar 05 '13 at 06:28
  • Very good point, Erwin. I have updated my answer to include the length test you have suggested. Thanks! – Nathan Wall Mar 05 '13 at 06:58
  • if the value exists but in different position then will this algorithm still works? – kta Jun 21 '18 at 05:44
  • This assumes the two arrays are sorted the same way. – Jeremy Chone Dec 17 '18 at 01:29
8

[ES6]

Top answer is good & enough.

But when you just want to compare its values are same you have to sort it before. here's no need sort code.

if(arr1.length == arr2.length && arr1.every((v) => arr2.indexOf(v) >= 0)) {
    console.log(true);
} else {
    console.log(false);
}

And.. I think using a 'some' instead of 'every' is better.

If those are not same, 'some' gives you a early exit. - very little early but early ;)

if(arr1.length == arr2.length && !arr1.some((v) => arr2.indexOf(v) < 0)) {
    console.log(true);
} else {
    console.log(false);
}
Tyson
  • 101
  • 1
  • 4
5

I would make use of underscore for this.

var same = (_.difference(arr1, arr2).length == 0)
staackuser2
  • 12,172
  • 4
  • 42
  • 40
  • 5
    This is incorrect. `_ = require('underscore'); _.difference(["a","c"], ["a","c","d"]).length;` returns: `0` Same for `lodash`. – alykoshin Mar 21 '16 at 19:23
3

The top answer is good, but I would also consider using Array.prototype:

Array.prototype.equals = function (arr) {
    return this.length == arr.length && this.every((u, i) => u === arr[i]);
}

console.log([1,2,3].equals([1,2,3])); // true
console.log([1,2,3].equals([1,3,3])); // false
// BUT!
console.log(["a",NaN,"b"].equals(["a",NaN,"b"])); // false, because NaN !== NaN

If you want it to work for NaNs too and distinguish +0 and -0, better use this:

Array.prototype.equals = function (arr) {
    function is(a, b) { // taken from the top answer
        return a === b && (a !== 0 || 1 / a === 1 / b) // false for +0 vs -0
            || a !== a && b !== b; // true for NaN vs NaN
    }
    return this.length == arr.length && this.every((u, i) => is(u, arr[i]));
}

console.log(["a",NaN,"b"].equals(["a",NaN,"b"])); // true
ibodi
  • 1,543
  • 3
  • 21
  • 40
2

Here's another one, without ES5 every:

function arrEq(arr1, arr2) {
  for (var i = 0; i < arr1.length; i++)
    if (arr1[i] != arr2[i])
      return false;
  return i == arr2.length;
}
BorisOkunskiy
  • 1,830
  • 1
  • 19
  • 24
1

I wanted to add some modification of the code made by 'Taihwan Hah' but could not leave a comment (the system told me so)

So here is my modifs:

function ArrayEquals(arr1,arr2){
    return arr1.length === arr2.length && !arr1.some((v) => arr2.indexOf(v) < 0) && !arr2.some((v) => arr1.indexOf(v) < 0);
}

basically, I had to check for but array because my arrays do not contains unique numbers.

LeRoss
  • 21
  • 1
1

(Although the question is much older than v9.0.0, but) since the question is about Node - starting from Node v9.0.0 you can use the built-in "util" module's isDeepStrictEqual(arr1, arr2) for comparing arrays (or objects, or anything for that matter)

const util = require('util');
let arr1 = [1,2,3];
let arr2 = [1,2,3];
let arr3 = [1,3,2];
console.log(util.isDeepStrictEqual(arr1, arr2)) // true
console.log(util.isDeepStrictEqual(arr1, arr3)) // false

Also works for NaN

There is also a non-strict version of this: https://nodejs.org/api/assert.html#assertdeepequalactual-expected-message

Scrandre
  • 141
  • 8
0

I would like to improve the answer from staackuser2 a little bit:

var same = (arr1.length === arr2.length) && (_.difference(arr1, arr2).length === 0)

or

var same = (_.difference(arr1, arr2).length === 0) && (_.difference(arr2, arr1).length === 0)
kalehmann
  • 4,821
  • 6
  • 26
  • 36
Robin Cai
  • 1
  • 2