[javascript] How to know if two arrays have the same values

I have these two arrays: one is filled with information from an ajax request and another stores the buttons the user clicks on. I use this code (I filled with sample numbers):

var array1 = [2, 4];
var array2 = [4, 2]; //It cames from the user button clicks, so it might be disordered.
array1.sort(); //Sorts both Ajax and user info.
array2.sort();
if (array1==array2) {
    doSomething();
}else{
    doAnotherThing();
}

But it always gives false, even if the two arrays are the same, but with different name. (I checked this in Chrome's JS Console). So, is there any way I could know if these two arrays contain the same? Why is it giving false? How can I know which values in the first array are not in the second?

This question is related to javascript arrays compare

The answer is


You didn't seem to care about perf, not sure any of the other answer did either.

Here's some benchmarks for both sameArrayMembers (ie, [1,2,2] != [1,1,2]) as well as sameArrayMembersAsSet (ie, [1,2,2] == [1,1,2])

Didn't check for [1,1,2] same as [1,2] which I probably should given if you're claiming to check for sets than you shouldn't have the length check.

_x000D_
_x000D_
const tests = {
  'Maciej Krawczyk': (_arr1, _arr2) => {

    if (!Array.isArray(_arr1) || ! Array.isArray(_arr2) || _arr1.length !== _arr2.length)
      return false;

    var arr1 = _arr1.concat().sort();
    var arr2 = _arr2.concat().sort();

    for (var i = 0; i < arr1.length; i++) {

        if (arr1[i] !== arr2[i])
            return false;

    }

    return true;
  },
  'canbax': (a1, a2) => {
    const superSet = {};
    for (const i of a1) {
      const e = i + typeof i;
      superSet[e] = 1;
    }

    for (const i of a2) {
      const e = i + typeof i;
      if (!superSet[e]) {
        return false;
      }
      superSet[e] = 2;
    }

    for (let e in superSet) {
      if (superSet[e] === 1) {
        return false;
      }
    }

    return true;
  },
  'kennebec': (array1, array2) => {
    return array1.slice().sort().join(',')=== array2.slice().sort().join(',');
  },
  'Max Heiber': function() {
    const containsAll = (arr1, arr2) => 
        arr2.every(arr2Item => arr1.includes(arr2Item));
    return (arr1, arr2) => 
        containsAll(arr1, arr2) && containsAll(arr2, arr1);
  }(),
  'gman': (a, b) => {
    if (a.length !== b.length) { return false; }
    const counts = new Map();
    for (const v of a) {
      const count = counts.get(v) || 0;
      counts.set(v, count + 1);
    }
    for (const v of b) {
      const count = counts.get(v);
      if (!count) {   // undefined or 0, both mean arrays are not the same
        return false;
      }
      counts.set(v, count - 1);
    }
    return true;
  },
  'Bemmu': (a, b) => {
    if (Array.isArray(a) && Array.isArray(b) && a.length == b.length) {
      a = a.concat().sort()
      b = b.concat().sort()
      return a.reduce((acc,e,i) => acc && e === b[i], true)
    } else {
      return false;
    }
  },
  'Sandeep': (array1, array2) => {
    return JSON.stringify(array1.sort()) === JSON.stringify(array2.sort());
  },
  'camslice': (arr1, arr2) => {
    const arr1test = arr1.slice().sort();
    const arr2test = arr2.slice().sort();
    return !arr1test.some((val, idx) => val !== arr2test[idx]);
  },
  'Dimitrios Stefos': (arr1, arr2) => {
    if (!Array.isArray(arr1) || !Array.isArray(arr2) || arr1.length!=arr2.length)
        return false;

    return arr1.length==arr1.filter(word => arr2.includes(word)).length;
  },
  'SC1000': (arr1, arr2, opts) => {
    function vKey(i, v) {
      return (opts?.enforceOrder ? `${i}-` : '') + `${typeof v}-${v}`
    }

    if (arr1.length !== arr2.length) return false;

    const d1 = {};
    const d2 = {};  
    for (let i = arr1.length - 1; i >= 0; i--) {
      d1[vKey(i, arr1[i])] = true;
      d2[vKey(i, arr2[i])] = true;
    }

    for (let i = arr1.length - 1; i >= 0; i--) {
      const v = vKey(i, arr1[i]);
      if (d1[v] !== d2[v]) return false;
    }

    for (let i = arr2.length - 1; i >= 0; i--) {
      const v = vKey(i, arr2[i]);
      if (d1[v] !== d2[v]) return false;
    }

    return true
  },
  'Magnus Fohlström': (arr1, arr2) => {
        let count = (arr, val) => arr.reduce((count, curr) => (curr === val ? 1:0) + count, 0);
        return arr1.length === arr2.length && arr1.reduce((checks, val) =>
            checks.concat(count(arr1, val) === count(arr2, val)), []).every(check => check);
   },
};

// ----------------------------

function createExposedPromise() {
 const p = {};
 p.promise = new Promise((resolve, reject) => {
   p.resolve = resolve;
   p.reject = reject;
 });
 return p;
}

function assert(cond) {
  if (!cond) {
    log('assert');
    throw new Error();
  }
}

async function main() {
  await testResults(true, 'sameArrayMembers');
  await testResults(false, 'sameArrayMemembersAsSet');
  
  async function testResults(asSet, msg) {
    log(`\n=======[ ${msg} ] ============`);
    const suite = new Benchmark.Suite();
    let test;

    // reject if they fail simple test
    const a = [1,1,2];
    const b = [1,2,2];
    for (const [name, fn] of Object.entries(tests)) {
      if (fn(a, b) === asSet) {
        log(`${name} fails for ${msg}([${a}], [${b}])`);
      } else {    
        suite.add(name, () => test(fn));
      }
    }

    let endPromise;

    suite.on('cycle', event => log(String(event.target)));
    suite.on('complete', function() {
      log('Fastest is ' + this.filter('fastest').map('name'));
      endPromise.resolve();
    });

    async function runWith(num, title) {
      log(`------[ ${title} ] -----------`);

      const a = [];
      for (let i = 0; i < num; ++i) {
        a[i] = Math.random();
      }
      const b = [...a];
      const c = [...a]; c[c.length / 2 | 0]++;

      endPromise = createExposedPromise();

      test = (fn) => {
        assert(fn(a, b))
        assert(!fn(a, c));
      };

      suite.reset();
      suite.run({'async': true});
      await endPromise.promise;
    }

    await runWith(10, 'small (10)');
    await runWith(100, 'medium (100)');
    await runWith(10000, 'large (10000)');
  }
}
main();

function log(...args) {
  const elem = document.createElement('pre');
  elem.textContent = args.join(' ');
  document.body.appendChild(elem);
}
_x000D_
pre { margin: 0; }
_x000D_
<script src="https://unpkg.com/[email protected]/lodash.js"></script>
<script src="https://unpkg.com/[email protected]/benchmark.js"></script>
_x000D_
_x000D_
_x000D_

The results will probably change over time since JS engines get updated. Here's some results from 2020/09/28

Chrome 87

=======[ sameArrayMembers ] ============
canbax fails for sameArrayMembers([1,1,2], [1,2,2])
Max Heiber fails for sameArrayMembers([1,1,2], [1,2,2])
Dimitrios Stefos fails for sameArrayMembers([1,1,2], [1,2,2])
SC1000 fails for sameArrayMembers([1,1,2], [1,2,2])
------[ small (10) ] -----------
Maciej Krawczyk x 246,129 ops/sec ±0.84% (66 runs sampled)
kennebec x 182,234 ops/sec ±0.56% (64 runs sampled)
gman x 377,356 ops/sec ±1.55% (64 runs sampled)
Bemmu x 244,850 ops/sec ±0.76% (64 runs sampled)
Sandeep x 100,529 ops/sec ±1.53% (63 runs sampled)
camslice x 542,577 ops/sec ±0.68% (64 runs sampled)
Fastest is camslice
------[ medium (100) ] -----------
Maciej Krawczyk x 12,121 ops/sec ±1.40% (63 runs sampled)
kennebec x 10,219 ops/sec ±1.60% (63 runs sampled)
gman x 41,225 ops/sec ±1.63% (62 runs sampled)
Bemmu x 12,400 ops/sec ±1.10% (63 runs sampled)
Sandeep x 12,470 ops/sec ±0.50% (64 runs sampled)
camslice x 57,126 ops/sec ±0.54% (64 runs sampled)
Fastest is camslice
------[ large (10000) ] -----------
Maciej Krawczyk x 30.75 ops/sec ±0.86% (42 runs sampled)
kennebec x 27.35 ops/sec ±1.11% (38 runs sampled)
gman x 376 ops/sec ±0.46% (62 runs sampled)
Bemmu x 30.91 ops/sec ±0.77% (42 runs sampled)
Sandeep x 80.33 ops/sec ±0.54% (53 runs sampled)
camslice x 166 ops/sec ±0.44% (61 runs sampled)
Fastest is gman

=======[ sameArrayMemembersAsSet ] ============
Maciej Krawczyk fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
kennebec fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
gman fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
Bemmu fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
Sandeep fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
camslice fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
------[ small (10) ] -----------
canbax x 110,826 ops/sec ±2.07% (63 runs sampled)
Max Heiber x 2,699,807 ops/sec ±1.31% (63 runs sampled)
Dimitrios Stefos x 2,910,096 ops/sec ±0.65% (62 runs sampled)
SC1000 x 59,989 ops/sec ±2.61% (63 runs sampled)
Fastest is Dimitrios Stefos
------[ medium (100) ] -----------
canbax x 9,624 ops/sec ±2.20% (53 runs sampled)
Max Heiber x 88,945 ops/sec ±0.71% (64 runs sampled)
Dimitrios Stefos x 94,425 ops/sec ±0.51% (65 runs sampled)
SC1000 x 5,742 ops/sec ±0.74% (33 runs sampled)
Fastest is Dimitrios Stefos
------[ large (10000) ] -----------
canbax x 59.85 ops/sec ±1.69% (46 runs sampled)
Max Heiber x 13.50 ops/sec ±0.87% (26 runs sampled)
Dimitrios Stefos x 15.40 ops/sec ±0.89% (30 runs sampled)
SC1000 x 37.42 ops/sec ±1.47% (40 runs sampled)
Fastest is canbax

Firefox 80

=======[ sameArrayMembers ] ============
canbax fails for sameArrayMembers([1,1,2], [1,2,2])
Max Heiber fails for sameArrayMembers([1,1,2], [1,2,2])
Dimitrios Stefos fails for sameArrayMembers([1,1,2], [1,2,2])
SC1000 fails for sameArrayMembers([1,1,2], [1,2,2])
------[ small (10) ] -----------
Maciej Krawczyk x 118,391 ops/sec ±0.52% (65 runs sampled)
kennebec x 70,254 ops/sec ±0.40% (67 runs sampled)
gman x 201,659 ops/sec ±3.23% (57 runs sampled)
Bemmu x 118,133 ops/sec ±0.67% (64 runs sampled)
Sandeep x 69,484 ops/sec ±1.40% (65 runs sampled)
camslice x 130,443 ops/sec ±0.55% (65 runs sampled)
Fastest is gman
------[ medium (100) ] -----------
Maciej Krawczyk x 11,418 ops/sec ±2.81% (61 runs sampled)
kennebec x 7,278 ops/sec ±1.37% (41 runs sampled)
gman x 19,748 ops/sec ±6.60% (53 runs sampled)
Bemmu x 11,535 ops/sec ±1.09% (62 runs sampled)
Sandeep x 8,234 ops/sec ±1.46% (45 runs sampled)
camslice x 14,277 ops/sec ±3.08% (60 runs sampled)
Fastest is gman
------[ large (10000) ] -----------
Maciej Krawczyk x 65.25 ops/sec ±2.13% (49 runs sampled)
kennebec x 47.73 ops/sec ±0.82% (51 runs sampled)
gman x 210 ops/sec ±3.54% (54 runs sampled)
Bemmu x 66.90 ops/sec ±0.53% (50 runs sampled)
Sandeep x 63.13 ops/sec ±1.59% (48 runs sampled)
camslice x 115 ops/sec ±1.36% (56 runs sampled)
Fastest is gman

=======[ sameArrayMemembersAsSet ] ============
Maciej Krawczyk fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
kennebec fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
gman fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
Bemmu fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
Sandeep fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
camslice fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
------[ small (10) ] -----------
canbax x 79,433 ops/sec ±1.11% (57 runs sampled)
Max Heiber x 1,822,200 ops/sec ±0.92% (65 runs sampled)
Dimitrios Stefos x 2,258,820 ops/sec ±0.48% (65 runs sampled)
SC1000 x 35,784 ops/sec ±1.42% (63 runs sampled)
Fastest is Dimitrios Stefos
------[ medium (100) ] -----------
canbax x 6,726 ops/sec ±0.60% (38 runs sampled)
Max Heiber x 41,620 ops/sec ±1.08% (65 runs sampled)
Dimitrios Stefos x 53,041 ops/sec ±1.61% (64 runs sampled)
SC1000 x 3,450 ops/sec ±0.56% (64 runs sampled)
Fastest is Dimitrios Stefos
------[ large (10000) ] -----------
canbax x 44.18 ops/sec ±5.87% (42 runs sampled)
Max Heiber x 5.62 ops/sec ±4.79% (19 runs sampled)
Dimitrios Stefos x 6.77 ops/sec ±1.21% (21 runs sampled)
SC1000 x 24.18 ops/sec ±3.50% (36 runs sampled)
Fastest is canbax

Safari 14

=======[ sameArrayMembers ] ============
canbax fails for sameArrayMembers([1,1,2], [1,2,2])
Max Heiber fails for sameArrayMembers([1,1,2], [1,2,2])
Dimitrios Stefos fails for sameArrayMembers([1,1,2], [1,2,2])
SC1000 fails for sameArrayMembers([1,1,2], [1,2,2])
------[ small (10) ] -----------
Maciej Krawczyk x 142,798 ops/sec ±0.50% (65 runs sampled)
kennebec x 118,073 ops/sec ±1.12% (63 runs sampled)
gman x 760,109 ops/sec ±0.46% (66 runs sampled)
Bemmu x 136,265 ops/sec ±0.48% (63 runs sampled)
Sandeep x 69,868 ops/sec ±0.44% (64 runs sampled)
camslice x 155,548 ops/sec ±0.45% (64 runs sampled)
Fastest is gman
------[ medium (100) ] -----------
Maciej Krawczyk x 8,479 ops/sec ±0.52% (46 runs sampled)
kennebec x 5,992 ops/sec ±2.54% (34 runs sampled)
gman x 83,390 ops/sec ±0.37% (64 runs sampled)
Bemmu x 8,615 ops/sec ±0.56% (63 runs sampled)
Sandeep x 5,943 ops/sec ±0.67% (64 runs sampled)
camslice x 8,753 ops/sec ±0.45% (47 runs sampled)
Fastest is gman
------[ large (10000) ] -----------
Maciej Krawczyk x 62.66 ops/sec ±0.87% (51 runs sampled)
kennebec x 46.46 ops/sec ±0.66% (48 runs sampled)
gman x 615 ops/sec ±2.33% (60 runs sampled)
Bemmu x 60.98 ops/sec ±1.28% (52 runs sampled)
Sandeep x 49.11 ops/sec ±2.07% (47 runs sampled)
camslice x 66.33 ops/sec ±4.44% (50 runs sampled)
Fastest is gman

=======[ sameArrayMemembersAsSet ] ============
Maciej Krawczyk fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
kennebec fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
gman fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
Bemmu fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
Sandeep fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
camslice fails for sameArrayMemembersAsSet([1,1,2], [1,2,2])
------[ small (10) ] -----------
canbax x 167,041 ops/sec ±0.63% (64 runs sampled)
Max Heiber x 1,281,054 ops/sec ±0.74% (59 runs sampled)
Dimitrios Stefos x 1,127,639 ops/sec ±0.98% (64 runs sampled)
SC1000 x 112,824 ops/sec ±0.37% (64 runs sampled)
Fastest is Max Heiber
------[ medium (100) ] -----------
canbax x 8,784 ops/sec ±0.53% (47 runs sampled)
Max Heiber x 37,824 ops/sec ±0.52% (65 runs sampled)
Dimitrios Stefos x 41,238 ops/sec ±0.85% (63 runs sampled)
SC1000 x 6,181 ops/sec ±0.61% (35 runs sampled)
Fastest is Dimitrios Stefos
------[ large (10000) ] -----------
canbax x 63.83 ops/sec ±2.46% (49 runs sampled)
Max Heiber x 5.41 ops/sec ±0.52% (18 runs sampled)
Dimitrios Stefos x 6.02 ops/sec ±1.32% (19 runs sampled)
SC1000 x 42.25 ops/sec ±1.45% (45 runs sampled)
Fastest is canbax

A function to Compare two Arrays, to check if both has same elements. Even if they are out of order...

It's good for simple arrays. [String,Number,Boolean,null,NaN].

I don't use .sort(), it modifies the original array. Some say's its bad...

Caution. This function is limited it can't compare Objects"[],{}" or functions within these Arrays, arrays it's self are Objects.

   let arraysHasSameElements = (arr1, arr2) => {
        let count =
            // returns counting of occurrences.
            (arr, val) => arr.reduce((count, curr) => (curr === val ? 1 : 0) + count, 0);

        /* this will return true if lengths of the arrays is equal.
           then compare them.*/
        return arr1.length === arr2.length

            // compare arr1 against arr2.
            && arr1.reduce((checks, val) =>

                /*  creating array of checking if a value has equal amount of occurrences
                    in both arrays, then adds true 'check'. */
                checks.concat(count(arr1, val) === count(arr2, val)), [])

                // checking if each check is equal to true, then .every() returns true.
                .every(check => check);
    }

    let arr1 = ['',-99,true,NaN,21,null,false,'help',-99,'help',NaN], 
        arr2 = [null,-99,'',NaN,NaN,false,true,-99,'help',21,'help'];
    arraysHasSameElements(arr1, arr2); //true

    let arr3 = [false,false,false,false,false,false], 
        arr4 = [false,false,false,false,false,false]
    arraysHasSameElements(arr3, arr4); //true


    // here we have uncommented version.
    let arraysHasSameElements = (arr1, arr2) => {
        let count = (arr, val) => arr.reduce((count, curr) => (curr === val ? 1:0) + count, 0);
        return arr1.length === arr2.length && arr1.reduce((checks, val) =>
            checks.concat(count(arr1, val) === count(arr2, val)), []).every(check => check);
    }


What about this? ES 2017 i suppose:

_x000D_
_x000D_
const array1 = [1, 3, 5];_x000D_
const array2 = [1, 5, 3];_x000D_
_x000D_
const isEqual = (array1.length === array2.length) && (array1.every(val => array2.includes(val)));_x000D_
console.log(isEqual);
_x000D_
_x000D_
_x000D_

1st condition checks if both arrays have same length and 2nd condition checks if 1st array is a subset of the 2nd array. Combining these 2 conditions should then result in comparison of all items of the 2 arrays irrespective of the ordering of elements.

The above code will only work if both arrays have non-duplicate items.


Array.prototype.compare = function(testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) { //To test values in nested arrays
            if (!this[i].compare(testArr[i])) return false;
        }
        else if (this[i] !== testArr[i]) return false;
    }
    return true;
}

var array1 = [2, 4];
var array2 = [4, 2];
if(array1.sort().compare(array2.sort())) {
    doSomething();
} else {
    doAnotherThing();
}

Maybe?


Another one line solution:

array1.concat(array2).filter((item, index, currentArr) => currentArr.lastIndexOf(item) == currentArr.indexOf(item)).length == 0;

or

[...array1, ...array2].filter((item, index, currentArr) => currentArr.lastIndexOf(item) == currentArr.indexOf(item)).length == 0;

kindly check this answer

var arr1= [12,18];
var arr2= [12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17];
for(i=0;i<arr1.length;i++)
{
var array1=arr1[i];
for(j=0;j<arr2.length;j++)
{
    var array2=arr2[j];
    if(array1==array2)
    {
return true;
    }
}
}

Most of the other solutions use sort, O(n*log n), use libraries or have O(n^2) complexity.

Here is a pure Javascript solution with linear complexity, O(n):

/**
 * Check if two arrays of strings or numbers have the same values
 * @param {string[]|number[]} arr1
 * @param {string[]|number[]} arr2
 * @param {Object} [opts]
 * @param {boolean} [opts.enforceOrder] - By default (false), the order of the values in the arrays doesn't matter.
 * @return {boolean}
 */
function compareArrays(arr1, arr2, opts) {

  function vKey(i, v) {
    return (opts?.enforceOrder ? `${i}-` : '') + `${typeof v}-${v}`
  }

  if (arr1.length !== arr2.length) return false;

  const d1 = {};
  const d2 = {};  
  for (let i = arr1.length - 1; i >= 0; i--) {
    d1[vKey(i, arr1[i])] = true;
    d2[vKey(i, arr2[i])] = true;
  }
  
  for (let i = arr1.length - 1; i >= 0; i--) {
    const v = vKey(i, arr1[i]);
    if (d1[v] !== d2[v]) return false;
  }

  for (let i = arr2.length - 1; i >= 0; i--) {
    const v = vKey(i, arr2[i]);
    if (d1[v] !== d2[v]) return false;
  }

  return true
}

Tests:

arr1= [1, 2]
arr2= [1, 2]
compareArrays(arr1, arr2) => true
compareArrays(arr1, arr2, {enforceOrder: true}) => true
-------
arr1= [1, 2]
arr2= [2, 1]
compareArrays(arr1, arr2) => true
compareArrays(arr1, arr2, {enforceOrder: true}) => false
-------
arr1= [2, 1]
arr2= [1, 2]
compareArrays(arr1, arr2) => true
compareArrays(arr1, arr2, {enforceOrder: true}) => false
-------
arr1= [2, 2]
arr2= [1, 2]
compareArrays(arr1, arr2) => false
compareArrays(arr1, arr2, {enforceOrder: true}) => false
-------
arr1= [1, 2]
arr2= [1, 2, 3]
compareArrays(arr1, arr2) => false
compareArrays(arr1, arr2, {enforceOrder: true}) => false
-------
arr1= ["1"]
arr2= [1]
compareArrays(arr1, arr2) => false
compareArrays(arr1, arr2, {enforceOrder: true}) => false
-------
arr1= ["1", 2]
arr2= [2, "1"]
compareArrays(arr1, arr2) => true
compareArrays(arr1, arr2, {enforceOrder: true}) => false
-------
arr1= []
arr2= []
compareArrays(arr1, arr2) => true
compareArrays(arr1, arr2, {enforceOrder: true}) => true

I have another way based on the accepted answer.

function compareArrays(array1, array2) {

    if (
        !Array.isArray(array1)
        || !Array.isArray(array2)
        || array1.length !== array2.length
    ) return false;

    var first = array1.sort().map(value => (String(value))).join();
    var second = array2.sort().map(value => (String(value))).join();

    return first == second ? true : false;
}

If you want to check only if two arrays have same values (regardless the number of occurrences and order of each value) you could do this by using lodash:

_.isEmpty(_.xor(array1, array2))

Short, simple and pretty!


I had simple integer values in a Game project
Had less number of values in each array, also, needed that original array untouched
So, I did the below, it worked fine. (Code edited to paste here)

var sourceArray = [1, 2, 3];
var targetArray = [3, 2, 1];

if (sourceArray.length !== targetArray.length) {
    // not equal
    // did something
    return false;
}

var newSortedSourceArray = sourceArray.slice().sort();
var newSortedTargetArray = targetArray.slice().sort();

if (newSortedSourceArray.toString() !== newSortedTargetArray.toString()) { // MAIN CHECK
    // not equal
    // did something
    return false;
}
else {
    // equal
    // did something
    // continued further below
}

// did some more work

return true;

Hope that helps.


If you only want to test for primitive values, you can try:

if(JSON.stringify(arr1.sort()) !== JSON.stringify(arr2.sort())) {
  console.log('invalid');
}

Answering after long time but hope this will help somebody who looking for a simple solution and modern newbies.

Now we can achieve this using multiple libraries like lodash, underscore, etc. (These becomes part of the project nowadays due to simplicity, multiple features and high usage)

You can use intersection from lodash library.

_.intersection(['2-1', '1'], ['2-2', '3-1', '2-1']); 
// => ['2-1']

This will work for any data type..


Simple Solution to compare the two arrays:

var array1 = [2, 4];
var array2 = [4, 2];

array1.sort();
array2.sort();

if (array1[0] == array2[0]) {
    console.log("Success");
}else{
    console.log("Wrong");
}

Try this

function arraysEqual(arr1, arr2){
    if (!Array.isArray(arr1) || !Array.isArray(arr2) || arr1.length!=arr2.length)
        return false;

    return arr1.length==arr1.filter(word => arr2.includes(word)).length;
}

When you compare those two arrays, you're comparing the objects that represent the arrays, not the contents.

You'll have to use a function to compare the two. You could write your own that simply loops though one and compares it to the other after you check that the lengths are the same.


You can use reduce instead of loops to appear clever, but at the risk of having your fellow developers think of you as a smart-ass.

function isArrayContentSame(a, b) {
  if (Array.isArray(a) && Array.isArray(b) && a.length == b.length) {
    a = a.concat().sort()
    b = b.concat().sort()
    return a.reduce((acc,e,i) => acc && e === b[i], true)
  } else {
    return false;
  }
}

Object equality check:JSON.stringify(array1.sort()) === JSON.stringify(array2.sort())

The above test also works with arrays of objects in which case use a sort function as documented in http://www.w3schools.com/jsref/jsref_sort.asp

Might suffice for small arrays with flat JSON schemas.


Our aim is basically to check whether 2 arrays are equal sets. set is the mathematically defined set. Fastest sorting asymptotically takes O(nlog(n)) time. So If you sort an array, it would take at least O(nlog(n)) time. But you can do this task faster, which asymptotically takes O(n) time (average case not worst case) with a dictionary data structure. In JS, a dictionary is simply an object with keys and values.

/** assumes array elements are primitive types
* check whether 2 arrays are equal sets.
* @param  {} a1 is an array
* @param  {} a2 is an array
*/
function areArraysEqualSets(a1, a2) {
  const superSet = {};
  for (const i of a1) {
    const e = i + typeof i;
    superSet[e] = 1;
  }

  for (const i of a2) {
    const e = i + typeof i;
    if (!superSet[e]) {
      return false;
    }
    superSet[e] = 2;
  }

  for (let e in superSet) {
    if (superSet[e] === 1) {
      return false;
    }
  }

  return true;
}

Note that this function works with arrays of primitive types and assumes a1 and a2 are arrays.


If your array items are not objects- if they are numbers or strings, for example, you can compare their joined strings to see if they have the same members in any order-

var array1= [10, 6, 19, 16, 14, 15, 2, 9, 5, 3, 4, 13, 8, 7, 1, 12, 18, 11, 20, 17];
var array2= [12, 18, 20, 11, 19, 14, 6, 7, 8, 16, 9, 3, 1, 13, 5, 4, 15, 10, 2, 17];

if(array1.sort().join(',')=== array2.sort().join(',')){
    alert('same members');
}
else alert('not a match');

Using ES6

We'll use Ramda's equals function, but instead we can use Lodash's or Underscore's isEqual:

const R = require('ramda');

const arraysHaveSameValues = (arr1, arr2) => R.equals( [...arr1].sort(), [...arr2].sort() )

Using the spread opporator, we avoid mutating the original arrays, and we keep our function pure.


If you want to compare two arrays and check if any object is same in both arrays it will works. Example :

Array1 = [a,b,c,d]
Array2 = [d,e,f,g]

Here, 'd' is common in both array so this function will return true value.

  cehckArray(array1, array2) {
    for (let i = 0; i < array1.length; i++) {
      for (let j = 0; j < array2.length; j++) {
        if (array1[i] === array2[j]) {
          return true;
        }
      }
    }
    // Return if no common element exist 
    return false;
  }

Simple solution for shallow equality using ES6:

const arr1test = arr1.slice().sort()
const arr2test = arr2.slice().sort()
const equal = !arr1test.some((val, idx) => val !== arr2test[idx])

Creates shallow copies of each array and sorts them. Then uses some() to loop through arr1test values, checking each value against the value in arr2test with the same index. If all values are equal, some() returns false, and in turn equal evaluates to true.

Could also use every(), but it would have to cycle through every element in the array to satisfy a true result, whereas some() will bail as soon as it finds a value that is not equal:

const equal = arr1test.every((val, idx) => val === arr2test[idx])

Why your code didn't work

JavaScript has primitive data types and non-primitive data types.

For primitive data types, == and === check whether the things on either side of the bars have the same value. That's why 1 === 1 is true.

For non-primitive data types like arrays, == and === check for reference equality. That is, they check whether arr1 and arr2 are the same object. In your example, the two arrays have the same objects in the same order, but are not equivalent.

Solutions

Two arrays, arr1 and arr2, have the same members if and only if:

  • Everything in arr2 is in arr1

AND

  • Everything in arr1 is in arr2

So this will do the trick (ES2016):

const containsAll = (arr1, arr2) => 
                arr2.every(arr2Item => arr1.includes(arr2Item))

const sameMembers = (arr1, arr2) => 
                        containsAll(arr1, arr2) && containsAll(arr2, arr1);

sameMembers(arr1, arr2); // `true`

This second solution using Underscore is closer to what you were trying to do:

arr1.sort();
arr2.sort();

_.isEqual(arr1, arr2); // `true`

It works because isEqual checks for "deep equality," meaning it looks at more than just reference equality and compares values.

A solution to your third question

You also asked how to find out which things in arr1 are not contained in arr2.

This will do it (ES2015):

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 2, 1];

arr1.filter(arr1Item => !arr2.includes(arr1Item)); // `[4]`

You could also use Underscore's difference: method:

_.difference(arr1, arr2); // `[4]`

UPDATE

See @Redu's comment—my solution is for sameMembers, but what you may have in mind is sameMembersInOrder also-known-as deepEquals.

UPDATE 2

If you don't care about the order of the members of the arrays, ES2015+'s Set may be a better data structure than Array. See the MDN notes on how to implement isSuperset and difference using dangerous monkey-patching.


If you are using the Prototype Framework, you can use the intersect method of an array to find out of they are the same (regardless of the order):

var array1 = [1,2];
var array2 = [2,1];

if(array1.intersect(array2).length === array1.length) {
    alert("arrays are the same!");
}

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to compare

Checking for duplicate strings in JavaScript array How to compare two files in Notepad++ v6.6.8 How to compare LocalDate instances Java 8 Comparing the contents of two files in Sublime Text comparing elements of the same array in java How to compare two dates along with time in java bash string compare to multiple correct values Query comparing dates in SQL How to compare two java objects Comparing two integer arrays in Java