使用 lodash 比较锯齿状数组(项目存在无序) [英] Using lodash to compare jagged arrays (items existence without order)
问题描述
我知道我可以使用循环来做到这一点,但我正在尝试找到一种优雅的方式来做到这一点:
I know I can do it using loops, but I'm trying to find an elegant way of doing this:
我有两个交错数组(数组数组):
I have two jagged arrays (array of arrays):
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
我想用lodash
来确认上面两个锯齿状数组是一样的.相同"是指 array1
中没有不包含在 array2
中的项目.请注意,锯齿状数组中的项目实际上是数组.所以我想在内部数组之间进行比较.
I want to use lodash
to confirm that the above two jagged arrays are the same. By 'the same' I mean that there is no item in array1
that is not contained in array2
. Notice that the items in jagged array are actually arrays. So I want to compare between inner arrays.
在检查这些项目之间的相等性方面:
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.
更新:原来的问题是关于数组"的(而不是锯齿状数组),多年来许多人讨论(并添加了答案)关于比较简单的一维数组(没有注意到问题中提供的示例实际上与他们期望的简单一维数组并不相似).
UPDATE: Original question was talking about to "arrays" (instead of jagged arrays) and for years many people discussed (and added answers) about comparing simple one-dimensional arrays (without noticing that the examples provided in the question were not actually similar to the simple one-dimensional arrays they were expecting).
推荐答案
如果对外层数组排序,可以使用 _.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屋!