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

2019-01-26 03:04发布

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?

2条回答
Deceive 欺骗
2楼-- · 2019-01-26 03:24

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.

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

DEMO

查看更多
贼婆χ
3楼-- · 2019-01-26 03:27

Maybe difference is what you are looking for:

_(hand).difference(colors).length === 0
查看更多
登录 后发表回答