2
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

2
  • Will a always contain more (or the same) elements as b? Commented Dec 27, 2018 at 5:32
  • @CertainPerformance yes Commented Dec 27, 2018 at 5:32

4 Answers 4

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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)

1 Comment

Yes. I like this technique without lodash. Thank you
2

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>

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.