39

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?

Wiseguy
  • 19,843
  • 8
  • 62
  • 79
ThomasReggi
  • 48,606
  • 78
  • 218
  • 380

2 Answers2

44

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

Felix Kling
  • 756,363
  • 169
  • 1,062
  • 1,111
  • 1
    Thanks, no matter how many times I read the underscore docs I can rarely think of these solutions when I need them. – ThomasReggi Jan 02 '13 at 22:30
  • 2
    as you say it's not working if the lements are not unique and it also doesn't work if you want to check the order: I created I gist to solve it with these needs: https://gist.github.com/timaschew/891632094c8bfcb73c38 – timaschew Jan 18 '16 at 01:08
  • 3
    _.difference(subset, superset).length === 0 – Mahesh K Aug 09 '17 at 13:43
21

Maybe difference is what you are looking for:

_(hand).difference(colors).length === 0
Sergey Berezovskiy
  • 224,436
  • 37
  • 411
  • 441