Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I test if one array is a subset of another? [closed]

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?

like image 760
ThomasReggi Avatar asked Jan 02 '13 22:01

ThomasReggi


People also ask

How do you check if an array is subset of another array 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.

How do you check if an array is a subarray of another array?

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.

How do you check if an array is a subset of another in SQL?

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.


2 Answers

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

like image 59
Felix Kling Avatar answered Sep 22 '22 23:09

Felix Kling


Maybe difference is what you are looking for:

_(hand).difference(colors).length === 0 
like image 42
Sergey Berezovskiy Avatar answered Sep 20 '22 23:09

Sergey Berezovskiy