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?
Naive Approach to Find whether an array is subset of another array. Use two loops: The outer loop picks all the elements of arr2[] one by one. The inner loop linearly searches for the element picked by the outer loop. If all elements are found then return 1, else return 0.
Simple Approach: A simple approach is to run two nested loops and generate all subarrays of the array A[] and use one more loop to check if any of the subarray of A[] is equal to the array B[]. Efficient Approach : An efficient approach is to use two pointers to traverse both the array simultaneously.
If you can populate a one column table with the values that you need to test against then you could do this. If the count is equal to the number of values you're testing against then the array forms a subset. Of course this assumes that you're using a SQL variant with intersect. Dems' solution should work everywhere.
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
Maybe difference is what you are looking for:
_(hand).difference(colors).length === 0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With