开发者

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?


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


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!


Sort the arrays and compare their values one by one.

function arrayCompare(_arr1, _arr2) {
    if (
      !Array.isArray(_arr1)
      || !Array.isArray(_arr2)
      || _arr1.length !== _arr2.length
      ) {
        return false;
      }
    
    // .concat() to not mutate arguments
    const arr1 = _arr1.concat().sort();
    const arr2 = _arr2.concat().sort();
    
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false;
         }
    }
    
    return true;
}


Why your code didn't work

In JavaScript, for non-primitive data types like arrays, == and === check for reference equality (leaving aside type conversions that == may perform). That is, they check whether arr1 and arr2 are the same object in memory. In your example, the two arrays have the same elements in the same order, but are not equal.

Here's an example that hopefully builds the intuition that false is the right result for [1] === [1]:

const x = [1];
const y = [1];
x === y; // false
x[0] = 200;
console.log(x); // "Array [ 200 ]"
console.log(y); // "Array [ 1 ]"
x === y; // false

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.

Update 3

If order doesn't matter, it's still better to use sets. But if you must use arrays, this solution has better time complexity than the one I gave earlier:

function sameMembers(arr1, arr2) {
    const set1 = new Set(arr1);
    const set2 = new Set(arr2);
    return arr1.every(item => set2.has(item)) &&
        arr2.every(item => set1.has(item))
}


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?


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.


What about this? ES 2017 i suppose:

const array1 = [1, 3, 5];
const array2 = [1, 5, 3];

const isEqual = (array1.length === array2.length) && (array1.every(val => array2.includes(val)));
console.log(isEqual);

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.


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.


For ES6

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


let difference = array1.filter(x => !array2.includes(x));

console.log("equals", difference?.length != 0 ? false : true)


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.


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.


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.


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


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


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.

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);
}
pre { margin: 0; }
<script src="https://unpkg.com/lodash@4.17.20/lodash.js"></script>
<script src="https://unpkg.com/benchmark@2.1.4/benchmark.js"></script>

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


  1. Check if two arrays have the same values but may not be in the same order

function compareArr(arr1, arr2) {
  return arr1.sort().join(',') == arr2.sort().join(',');
}

console.log(compareArr([1,2,3],[1,2,3])); // returns true
console.log(compareArr([1,2,3],[3,2,1])); // returns true
console.log(compareArr([1,2,3],[3,4,1])); // returns false

  1. Check if two arrays have the same value and the same order (just don't sort it.)

function compareArrOrder(arr1, arr2) {
  return arr1.join(',') == arr2.join(',');
}

console.log(compareArrOrder([1,2,3],[1,2,3])); // returns true
console.log(compareArrOrder([1,2,3],[3,2,1])); // returns false
console.log(compareArrOrder([1,2,3],[3,4,1])); // returns false


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


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;


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 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])


Code & Explanation

function arrayEquals(arr1, arr2) {
  // compare array lengths, if not equal then skip.
  if (arr1.length !== arr2.length) return false;

  // setup a variable of the array length
  let i = arr1.length;

  // iterate through every element in arr1 basically...
  while (i--) {
    // if arr2 doesn't include x element from arr1, return false
    if (!arr2.includes(arr1[i])) return false;

    // passes tests and checks out
  };
  return true;
}

// works with multiple types
let foo = ["foo", "bar", 1, 2, true];
let bar = ["bar", 2, true, "foo", 1];

console.log(foo,bar,"Should return true: " + arrayEquals(foo, bar));

let fob = ["bar", "foo"];
let oar = ["oar", "foo"];

console.log(fob,oar,"Should return false (bar ≠ oar): " + arrayEquals(fob, oar));

Disclaimer

This only supports simple types like your strings, numbers, booleans, etc. It won't really look far into your objects or arrays unless you edit the code to make it recursive, however that doesn't really seem like an issue in terms of answering the question itself. You provided numbers, so my answer will work with numbers.


The most easiest way to get the result is below

const array1 = [1,2,3,4]

const array2 = [3,4,5,6]

const result = array1.filter(arr => array2.includes(arr))

console.log(result)


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


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


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


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


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

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


This worked fine for me, but I don't understand why some people use the concat method on the arrays.

/**
 * 
 * @param {Array} firstArray 
 * @param {Array} secondArray 
 * @returns {boolean}
 */
function arrayIsEqual(firstArray, secondArray)
{
    if (
        !Array.isArray(firstArray) 
        || !Array.isArray(secondArray) 
        || firstArray.length !== secondArray.length
    ) {
        console.log('Bad params!\n');
        return false;
    }
    $bool = firstArray === secondArray || firstArray.every((x,i)=> Array.isArray(x) ? arrayIsEqual(x, secondArray[i]) : x === secondArray[i]);
    console.log($bool);
    return $bool;
}

let a = [1, 2];
let b = [3, 4];
let c = "Me and you";
let d = [1, [2, 3, 5], 4];
let e = [1, [2, 3, 5], 4];
let f = [1, [2, 3, 5], [4]];
let g = [1, [2, 3, 5], [4]];

arrayIsEqual(a, b);
arrayIsEqual(b, c);
arrayIsEqual(c, a);
arrayIsEqual(a, a);
arrayIsEqual(d, e);
arrayIsEqual(e, f);
arrayIsEqual(e, e);
arrayIsEqual(g, f);

Output

false
Bad params!

Bad params!

true
true
true
true
false
true
true
true
true


If the order of the array elements are not important, you could try

function arraysEqual<T>(a:T[], b:T[]) {
  if (a === b) return true;
  if (a == null || b == null) return false;
  if (a.length !== b.length) return false;


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

const arr1 = [1,2,3,4];
const arr2 = [3,2,1,4];
console.log(arraysEqual(arr1, arr2)) //true


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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜