Monday, May 20, 2024
150
rated 0 times [  153] [ 3]  / answers: 1 / hits: 17168  / 12 Years ago, wed, january 2, 2013, 12:00:00

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?


More From » underscore.js

 Answers
22

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


[#81121] Monday, December 31, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
hasanb

Total Points: 321
Total Questions: 102
Total Answers: 96

Location: Burkina Faso
Member since Fri, Sep 4, 2020
4 Years ago
;