Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
How to find all subsets of a set in JavaScript?
To find all subsets of a set in JavaScript, you can use the reduce() method along with map() to generate all possible combinations. A subset is any combination of elements from the original set, including the empty set and the set itself.
How It Works
The algorithm starts with an empty subset [[]] and for each element in the original array, it creates new subsets by adding that element to all existing subsets.
Example
const findAllSubsetsOfGivenSet = originalArrayValue =>
originalArrayValue.reduce(
(givenSet, setValue) => givenSet.concat(
givenSet.map(subset => [setValue, ...subset])
),
[[]]
);
console.log(findAllSubsetsOfGivenSet([8, 9]));
[ [], [ 8 ], [ 9 ], [ 9, 8 ] ]
Step-by-Step Breakdown
Let's trace through the algorithm with the array [8, 9]:
const findAllSubsetsOfGivenSet = originalArrayValue => {
return originalArrayValue.reduce((givenSet, setValue) => {
console.log(`Processing element: ${setValue}`);
console.log(`Current subsets:`, givenSet);
const newSubsets = givenSet.map(subset => [setValue, ...subset]);
console.log(`New subsets with ${setValue}:`, newSubsets);
const result = givenSet.concat(newSubsets);
console.log(`Combined result:`, result);
console.log('---');
return result;
}, [[]]);
};
console.log("Final result:", findAllSubsetsOfGivenSet([8, 9]));
Processing element: 8 Current subsets: [ [] ] New subsets with 8: [ [ 8 ] ] Combined result: [ [], [ 8 ] ] --- Processing element: 9 Current subsets: [ [], [ 8 ] ] New subsets with 9: [ [ 9 ], [ 9, 8 ] ] Combined result: [ [], [ 8 ], [ 9 ], [ 9, 8 ] ] --- Final result: [ [], [ 8 ], [ 9 ], [ 9, 8 ] ]
Example with Larger Set
const findAllSubsetsOfGivenSet = originalArrayValue =>
originalArrayValue.reduce(
(givenSet, setValue) => givenSet.concat(
givenSet.map(subset => [setValue, ...subset])
),
[[]]
);
console.log("Subsets of [1, 2, 3]:");
console.log(findAllSubsetsOfGivenSet([1, 2, 3]));
Subsets of [1, 2, 3]: [ [], [ 1 ], [ 2 ], [ 2, 1 ], [ 3 ], [ 3, 1 ], [ 3, 2 ], [ 3, 2, 1 ] ]
Key Points
- The algorithm generates 2^n subsets where n is the number of elements
- Each element can either be included or excluded from a subset
- The empty array
[]is always a subset - Order of elements in subsets follows the reverse of input order
Conclusion
Using reduce() with map() provides an elegant functional approach to generate all subsets. The algorithm efficiently builds subsets by expanding existing combinations with each new element.
Advertisements
