41

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?

3
  • Possible duplicate: stackoverflow.com/q/3115982/561731 Commented Jan 2, 2013 at 22:20
  • 3
    Looks like he is trying to determine if the array given has only the elements of the colors array in it. Commented Jan 2, 2013 at 22:23
  • @MrZander precicley, thanks for being so eloquent. Commented Jan 2, 2013 at 22:25

2 Answers 2

46

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

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks, no matter how many times I read the underscore docs I can rarely think of these solutions when I need them.
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: gist.github.com/timaschew/891632094c8bfcb73c38
_.difference(subset, superset).length === 0
22

Maybe difference is what you are looking for:

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

2 Comments

It should be _(hand).difference(colors).length === 0;: jsfiddle.net/GXGun/1 (you got it vice versa ;)). Nice solution though!
return !_(hand).difference(colors).length

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.