使用lodash来比较数组(项目存在而没有顺序) [英] using lodash to compare arrays (items existence without order)
问题描述
我知道我可以使用循环来做到这一点,但是我正在尝试找到一种优雅的方式来做到这一点:
I know I can do it using loops, but I am trying to find an elegant way of doing this:
我有两个数组:
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
我想用lodash确认两者相同. 相同"是指array1中没有未包含在array2中的项目.
I want to use lodash to confirm that the two are the same. By 'the same' I mean that there is no item in array1 that is not contained in array2.
在检查这些项目之间的相等性方面:
In terms of checking equality between these items:
['a', 'b'] == ['b', 'a']
或
['a', 'b'] == ['a', 'b']
因为字母始终是有序的,所以两者都可以工作.
both work since the letters will always be in order.
提前谢谢.
推荐答案
如果对外部数组进行排序,则可以使用 _.isEqual()
,因为内部数组已经排序.
If you sort the outer array, you can use _.isEqual()
since the inner array is already sorted.
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
_.isEqual(array1.sort(), array2.sort()); //true
请注意,.sort()
将使数组变异.如果这对您来说是个问题,请首先使用(例如).slice()
或传播运算符(...
)进行复制.
Note that .sort()
will mutate the arrays. If that's a problem for you, make a copy first using (for example) .slice()
or the spread operator (...
).
或者,按照丹尼尔·布迪克(Daniel Budick)在以下评论中建议的方式进行操作:
Or, do as Daniel Budick recommends in a comment below:
_.isEqual(_.sortBy(array1), _.sortBy(array2))
Lodash的sortBy()
不会使数组变异.
Lodash's sortBy()
will not mutate the array.
这篇关于使用lodash来比较数组(项目存在而没有顺序)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!