How to find all subsets of a set in JavaScript?

JavascriptWeb DevelopmentObject Oriented Programming

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 ] ]
raja
Published on 01-Sep-2020 11:29:54
Advertisements