Categories
JavaScript Answers

How to Find All Subsets of a Set in JavaScript?

Spread the love

Sometimes, we want to find all subsets of a set in JavaScript.

In this article, we’ll look at how to find all subsets of a set in JavaScript.

Find All Subsets of a Set in JavaScript

To find all subsets of a set in JavaScript, we can use the reduce method to get all subsets of a set.

For instance, we can write:

const getAllSubsets =
  theArray => theArray.reduce(
    (subsets, value) => subsets.concat(
      subsets.map(set => [value, ...set])
    ),
    [
      []
    ]
  );

console.log(getAllSubsets([1, 2, 3]));

to create the getAllSubsets function that takes the theArray array parameter.

We then call reduce on it with a callback that takes the subsets and value parameters.

We callsubsets.concat with the array created by subsets.map with a callback that takes the value and set entries and combine them into a new subset.

The 2nd argument is an array with an empty array in it, which is the initial value of subsets .

Therefore, when we call getAllSubsets with [1, 2, 3] , we get:

[]
[1]
[2]
[2, 1]
[3]
[3, 1]
[3, 2]
[3, 2, 1]

in the array.

Conclusion

To find all subsets of a set in JavaScript, we can use the reduce method to get all subsets of a set.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *