javascript 如何测试一个数组是否是另一个数组的子集?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14130104/
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
How do I test if one array is a subset of another?
提问by ThomasReggi
What's the best (cleanest) way to provide this sort of logic?
提供这种逻辑的最佳(最干净)方式是什么?
var colors = ["red","white","blue"];
logic(colors,["red","green"]); //false
logic(colors,["red"]); //true
logic(colors,["red","purple"]); //false
logic(colors,["red","white"]); //true
logic(colors,["red","white","blue"]); //true
logic(colors,["red","white","blue","green"]); //false
logic(colors,["orange"]); //false
Possibly using underscore.js?
可能使用underscore.js?
回答by Felix Kling
Assuming each element in the array is unique: Compare the length of hand
with the length of the intersection of both arrays. If they are the same, all elements in hand
are also in colors
.
假设数组中的每个元素都是唯一的:将 的长度hand
与两个数组的交集的长度进行比较。如果它们相同,则中的所有元素hand
也都在 中colors
。
var result = (hand.length === _.intersection(hand, colors).length);