I need to get all possible subsets of an array.
Say I have this:
[1, 2, 3]
How do I get this?
[], [1], [2], [3], [1, 2], [2, 3], [1, 3], [1, 2, 3]
I am interested in all subsets. For subsets of specific length, refer to the following questions:
The number of subsets of an array is 2N where N is the size of the array. We basically generate N-bit binary string for all numbers in the range 0 to 2N – 1 and print array based on the string. If the ith index of the binary string is 1, that means the ith index of the array is included in the subset.
If a set contains 'n' elements, then the number of subsets of the set is 2n. Number of Proper Subsets of the Set: If a set contains 'n' elements, then the number of proper subsets of the set is 2n - 1. In general, number of proper subsets of a given set = 2m - 1, where m is the number of elements.
Yes there is a formula for the maximum number of subsets given a set of size N. If you do not want to include the null set, then the answer would be 2N−1. If you wish to know the derivation of this formula, please see this question.
So, in the case of an array, it would mean the number of elements in the array or the size of the array, 2^(size of the array) will be the number of subsets. Let us take in the case, an array of "a, b, c". Since this array has a size of 3, there would be 2^3=8 subsets.
Here is one more very elegant solution with no loops or recursion, only using the map and reduce array native functions.
const getAllSubsets = theArray => theArray.reduce( (subsets, value) => subsets.concat( subsets.map(set => [value,...set]) ), [[]] ); console.log(getAllSubsets([1,2,3]));
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