40

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
  • 20,522
  • 8
  • 65
  • 81
ThomasReggi
  • 55,053
  • 85
  • 237
  • 424

2 Answers2

45

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
  • 795,719
  • 175
  • 1,089
  • 1,143
  • 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
22

Maybe difference is what you are looking for:

_(hand).difference(colors).length === 0
Sergey Berezovskiy
  • 232,247
  • 41
  • 429
  • 459