var a = [["Green","Medium"],["Green","Small"],["Medium","Red"],["Red","Small"]];
var b = [["Green","Medium"],["Green","Small"],["Medium","Red"]];
所以我的结果将
[["Red","Small"]]
不是a.filter(x => !b.includes(x))
无效,因为所有元素都是数组。
我已经尝试过类似的事情
var diff = [];
a.forEach((res, i) => {
b.forEach((res2, j) => {
if (i === j && !_.isEqual(res, res2)) {
diff.push(res);
}
});
});
console.log(diff);
当不同元素位于最后位置时,此方法不起作用
答案 0 :(得分:3)
在lodash中,您可以使用_.differenceWith()
并提供_.isEqual()
作为比较器来执行深度比较:
const c = _.differenceWith(a, b, _.isEqual);
完整摘要:
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>
答案 1 :(得分:2)
对于不需要库的O(N)
解决方案,我通过对每个子数组的内容进行字符串化,将map
b
转换为Set
字符串,然后根据集合中是否包含filter
的字符串项来a
a
:
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
通常是O(1)
,不像includes
和indexOf
这样的数组方法)
答案 2 :(得分:2)
由于您已经在使用lodash,因此可以使用filter和every的组合来比较两个数组。
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>
答案 3 :(得分: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)