简体   繁体   中英

Difference between two array when elements are array

var a = [["Green","Medium"],["Green","Small"],["Medium","Red"],["Red","Small"]];

var b = [["Green","Medium"],["Green","Small"],["Medium","Red"]];

So my result will [["Red","Small"]]

Not that a.filter(x => !b.includes(x)) won't work because all element are array. I've tried something like that

    var diff = [];
    a.forEach((res, i) => {
      b.forEach((res2, j) => {
        if (i === j && !_.isEqual(res, res2)) {
          diff.push(res);
        }
      });
    });
console.log(diff);

This not working when different elements are last positions

In lodash, you can use _.differenceWith() and supply _.isEqual() as a comparator to perform a deep comparison:

const c = _.differenceWith(a, b, _.isEqual);

Full snippet:

 const a = [["Green","Medium"],["Green","Small"],["Medium","Red"],["Red","Small"]]; const b = [["Green","Medium"],["Green","Small"],["Medium","Red"]]; const c = _.differenceWith(a, b, _.isEqual); console.log(c); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script> 

For an O(N) solution that doesn't require a library, I'd map b to a Set of strings by stringifying the contents of each sub-array, then filter a by whether a 's stringified items are contained in the set:

 var a = [["Green","Medium"],["Green","Small"],["Medium","Red"],["Red","Small"]]; var b = [["Green","Medium"],["Green","Small"],["Medium","Red"]]; const bSet = new Set(b.map(arr => JSON.stringify(arr))); const aFiltered = a.filter(arr => !bSet.has(JSON.stringify(arr))); console.log(aFiltered); 

( Set.has is generally O(1) , unlike Array methods like includes and indexOf )

As you are already using lodash you can use combination of filter and every to compare two array.

 var a = [["Green","Medium"],["Green","Small"],["Medium","Red"],["Red","Small"]]; var b = [["Green","Medium"],["Green","Small"],["Medium","Red"]]; var unique = a.filter(a=> b.every(b=> !_.isEqual(a, b))); console.log(unique) 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script> 

var a = [["Green","Medium"],["Green","Small"],["Medium","Red"],["Red","Small"]];

var b = [["Green","Medium"],["Green","Small"],["Medium","Red"]];

var c = b.map(ele=>JSON.stringify(ele));

var p = a.filter(ele=>!c.includes(JSON.stringify(ele)))

console.log(p)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM