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?
2 个解决方案
#1
38
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的长度与两个数组的交集长度进行比较。如果它们相同,则手中的所有元素也都是颜色。
var result = (hand.length === _.intersection(hand, colors).length);
#2
17
Maybe difference is what you are looking for:
也许差异就是你要找的东西:
_(hand).difference(colors).length === 0
#1
38
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的长度与两个数组的交集长度进行比较。如果它们相同,则手中的所有元素也都是颜色。
var result = (hand.length === _.intersection(hand, colors).length);
#2
17
Maybe difference is what you are looking for:
也许差异就是你要找的东西:
_(hand).difference(colors).length === 0