How to find all subsets of a set in JavaScript?


To find all subsets of a set, use reduce() along with map() in JavaScript. Let’s say, we are passing the set [8,9] and finding the subsets.

Example

const findAllSubsetsoOfGivenSet =
originalArrayValue => originalArrayValue.reduce(
   (givenSet, setValue) => givenSet.concat(
      givenSet.map(givenSet => [setValue,...givenSet])
   ),
[[]]
);
console.log(findAllSubsetsoOfGivenSet([8,9]));

To run the above program, you need to use the following command −

node fileName.js.

Here, my file name is demo36.js.

Output

This will produce the following output.

PS C:\Users\Amit\JavaScript-code> node demo36.js
[ [], [ 8 ], [ 9 ], [ 9, 8 ] ]

Updated on: 01-Sep-2020

510 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements