Reputation: 3072
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
Upvotes: 2
Views: 85
Reputation: 1195
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)
Upvotes: 0
Reputation: 97130
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>
Upvotes: 3
Reputation: 13801
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>
Upvotes: 2
Reputation: 370689
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
)
Upvotes: 2