using lodash to compare arrays (items existence without order)

一笑奈何 提交于 2019-11-28 07:06:52

If you sort the outer array, you can use _.isEqual() since the inner array is already sorted.

var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
_.isEqual(array1.sort(), array2.sort()); //true

Note that .sort() will mutate the arrays. If that's a problem for you, make a copy first using (for example) .slice() or the spread operator (...).

Or, do as Daniel Budick recommends in a comment below:

_.isEqual(_.sortBy(array1), _.sortBy(array2))

Lodash's sortBy() will not mutate the array.

You can use lodashs xor for this

doArraysContainSameElements = _.xor(arr1, arr2).length === 0

By 'the same' I mean that there are is no item in array1 that is not contained in array2.

You could use flatten() and difference() for this, which works well if you don't care if there are items in array2 that aren't in array1. It sounds like you're asking is array1 a subset of array2?

var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];

function isSubset(source, target) {
    return !_.difference(_.flatten(source), _.flatten(target)).length;
}

isSubset(array1, array2); // → true
array1.push('d');
isSubset(array1, array2); // → false
isSubset(array2, array1); // → true

PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains , use as join('-') parametr character (can be utf) which is not used in strings

array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()

var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['b', 'a']];

var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();

console.log(r);

We can use _.difference function to see if there is any difference or not.

function isSame(arrayOne, arrayTwo) {
   var a = arrayOne,
       b = arrayTwo;

   if (arrayOne.length <= arrayTwo.length) {
      a = arrayTwo;
      b = arrayOne;
      return _.isEmpty(_.difference(a.sort(), b.sort()));
   } else {
      return false;
   }

}

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

I hope this will help you.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!