[英]Compare two different length arrays using lodash
如何使用lodash比较具有不同长度的两个数组? 第一个数组包含现有元素,第二个数组包含new和现有元素。 如何使用lodash获取新元素?
+---------+-----------------------+-----------------+
| Existing| Source of new element | Expected result |
+---------+-----------------------+-----------------+
| [] | [1] | [1] |
| [1,2] | [3,4] | [3, 4] |
| [1,2,3] | [3,4] | [4] |
+---------+-----------------------+-----------------+
我不明白为什么您需要lodash,因为已经建议使用Array#filter()
来完成它,这很简单,但是如果您想依赖lodash,请使用_.difference() 。
const a = [1, 2, 3], b = [3, 4]; console.log(_.difference(b, a));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
这是使用本机Array#filter()
和Array#includes()
的非常简单的过滤操作
let a = [1, 2, 3], b = [3, 4], unique = b.filter(e => !a.includes(e)) console.log(unique)
或者代替includes()
将第一个数组传递给Set
并使用Set#has()
let a = new Set([1, 2, 3]), b = [3, 4], unique = b.filter(e => !a.has(e)); console.log(unique)
您可以使用_.differenceWith ,并传递一个比较两个数组的比较器,如下所示:
const a = [1, 2, 3], b = [3, 4]; console.log(_.differenceWith(b, a, _.isEqual));
<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.10/lodash.min.js"></script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.