Javascript 使用 lodash 比较数组(项目存在无序)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29951293/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
using lodash to compare arrays (items existence without order)
提问by pQuestions123
I know I can do it using loops, but I am trying to find an elegant way of doing this:
我知道我可以使用循环来做到这一点,但我试图找到一种优雅的方式来做到这一点:
I have two arrays:
我有两个数组:
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
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.
我想用lodash来确认两者是一样的。“相同”是指 array1 中没有不包含在 array2 中的项目。
In terms of checking equality between these items:
在检查这些项目之间的相等性方面:
['a', 'b'] == ['b', 'a']
or
或者
['a', 'b'] == ['a', 'b']
both work since the letters will always be in order.
两者都有效,因为字母总是按顺序排列的。
Thanks in advance.
提前致谢。
回答by Trott
If you sort the outer array, you can use _.isEqual()since the inner array is already sorted.
如果对外部数组进行排序,则可以使用,_.isEqual()因为内部数组已经排序。
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
_.isEqual(array1.sort(), array2.sort()); //true
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 (...).
请注意,这.sort()将改变数组。如果这对您来说是个问题,请先使用(例如).slice()或展开运算符 ( ...)进行复制。
Or, do as Daniel Budick recommends in a comment below:
或者,按照 Daniel Budick 在以下评论中的建议进行操作:
_.isEqual(_.sortBy(array1), _.sortBy(array2))
Lodash's sortBy()will not mutate the array.
LodashsortBy()不会改变数组。
回答by Stephan Hoyer
You can use lodashs xorfor this
您可以xor为此使用 lodashs
doArraysContainSameElements = _.xor(arr1, arr2).length === 0
If you consider array [1, 1] to be different than array [1] then you may improve performance a bit like so:
如果您认为数组 [1, 1] 与数组 [1] 不同,那么您可以像这样提高性能:
doArraysContainSameElements = arr1.length === arr2.length === 0 && _.xor(arr1, arr2).length === 0
回答by Adam Boduch
By 'the same' I mean that there are is no item in array1 that is not contained in array2.
“相同”是指 array1 中没有不包含在 array2 中的项目。
You could use flatten() and difference() for this, which works well if you don't care if there are items in array2that aren'tin array1. It sounds like you're asking is array1 a subset of array2?
你可以使用展平()和差()用于此目的,效果很好,如果你是否有物品不在乎array2这是不是在array1。听起来您是在问array1 是 array2 的子集吗?
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['a', 'b']];
function isSubset(source, target) {
return !_.difference(_.flatten(source), _.flatten(target)).length;
}
isSubset(array1, array2); // → true
array1.push('d');
isSubset(array1, array2); // → false
isSubset(array2, array1); // → true
回答by J.Ko
There are already answers here, but here's my pure JS implementation. I'm not sure if it's optimal, but it sure is transparent, readable, and simple.
这里已经有了答案,但这是我的纯 JS 实现。我不确定它是否是最佳的,但它肯定是透明的、可读的和简单的。
// Does array a contain elements of array b?
const contains = (a, b) => new Set([...a, ...b]).size === a.length
const isEqualSet = (a, b) => contains(a, b) && contains(b, a)
The rationale in contains()is that if adoes contain all the elements of b, then putting them into the same set would not change the size.
的基本原理contains()是,如果a确实包含 的所有元素b,则将它们放入同一个集合中不会改变大小。
For example, if const a = [1,2,3,4]and const b = [1,2], then new Set([...a, ...b]) === {1,2,3,4}. As you can see, the resulting set has the same elements as a.
例如,如果const a = [1,2,3,4]和const b = [1,2],则new Set([...a, ...b]) === {1,2,3,4}。如您所见,结果集具有与 相同的元素a。
From there, to make it more concise, we can boil it down to the following:
从那里,为了使它更简洁,我们可以将其归结为以下内容:
const isEqualSet = (a, b) => {
const unionSize = new Set([...a, ...b])
return unionSize === a.length && unionSize === b.length
}
回答by Kamil Kie?czewski
PURE JS (works also when arrays and subarrays has more than 2 elements with arbitrary order). If strings contains ,use as join('-')parametr character (can be utf) which is not used in strings
PURE JS(当数组和子数组具有超过 2 个任意顺序的元素时也适用)。如果字符串包含,用作join('-')参数的字符(可以是 utf),它在字符串中未使用
array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join()
var array1 = [['a', 'b'], ['b', 'c']];
var array2 = [['b', 'c'], ['b', 'a']];
var r = array1.map(x=>x.sort()).sort().join() === array2.map(x=>x.sort()).sort().join();
console.log(r);
回答by Amitesh
We can use _.differencefunction to see if there is any difference or not.
我们可以使用_.difference函数来查看是否有任何差异。
function isSame(arrayOne, arrayTwo) {
var a = _.unique(arrayOne),
b = _.unique(arrayTwo);
if (a.length <= b.length) {
a = arrayTwo;
b = arrayOne;
return _.isEmpty(_.difference(a.sort(), b.sort()));
} else {
return false;
}
}
// examples
console.log(isSame([1, 2, 3], [1, 2, 3])); // true
console.log(isSame([1, 2, 4], [1, 2, 3])); // false
console.log(isSame([1, 2], [2, 3, 1])); // false
console.log(isSame([2, 3, 1], [1, 2])); // false
// Test cases pointed by Mariano Desanze, Thanks.
console.log(isSame([1, 2, 3], [1, 2, 2])); // false
console.log(isSame([1, 2, 2], [1, 2, 2])); // true
console.log(isSame([1, 2, 2], [1, 2, 3])); // false
I hope this will help you.
我希望这能帮到您。
回答by charliematters
Edit: I missed the multi-dimensional aspect of this question, so I'm leaving this here in case it helps people compare one-dimensional arrays
编辑:我错过了这个问题的多维方面,所以我把它留在这里以防它帮助人们比较一维数组
It's an old question, but I was having issues with the speed of using .sort()or sortBy(), so I used this instead:
这是一个老问题,但我在使用.sort()or的速度方面遇到了问题sortBy(),所以我改用了这个:
function arraysContainSameStrings(array1: string[], array2: string[]): boolean {
return (
array1.length === array2.length &&
array1.every((str) => array2.includes(str)) &&
array2.every((str) => array1.includes(str))
)
}
It was intended to fail fast, and for my purposes works fine.
它旨在快速失败,并且对我而言效果很好。

