使用lodash比较锯齿状数组(项存在而无顺序) [英] Using lodash to compare jagged arrays (items existence without order)

查看:56
本文介绍了使用lodash比较锯齿状数组(项存在而无顺序)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道我可以使用循环来做到这一点,但是我正在尝试找到一种优雅的方式来做到这一点:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆