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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 20:47:04  来源:igfitidea点击:

How do I test if one array is a subset of another?

javascriptunderscore.js

提问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 handwith the length of the intersection of both arrays. If they are the same, all elements in handare also in colors.

假设数组中的每个元素都是唯一的:将 的长度hand与两个数组的交集的长度进行比较。如果它们相同,则中的所有元素hand也都在 中colors

var result = (hand.length === _.intersection(hand, colors).length);

DEMO

演示

回答by Sergey Berezovskiy

Maybe differenceis what you are looking for:

也许不同的是你正在寻找什么:

_(hand).difference(colors).length === 0