Using lodash to compare jagged arrays (items existence without order) Using lodash to compare jagged arrays (items existence without order) arrays arrays

Using lodash to compare jagged arrays (items existence without order)


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

If you consider array [1, 1] to be different than array [1] then you may improve performance a bit like so:

doArraysContainSameElements = arr1.length === arr2.length === 0 && _.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); // → truearray1.push('d');isSubset(array1, array2); // → falseisSubset(array2, array1); // → true