Finding all possible subsets of an array in JavaScript

JavascriptWeb DevelopmentFront End Technology

We are required to write a JavaScript function that takes in an array of literals as the first and the only argument.

The function should construct and return an array of all possible subarrays that can be formed from the original array.

For example −

If the input array is −

const arr = [1, 2, 3];

Then the output should be −

const output = [
   [2],
   [1],
   [3],
   [1,2,3],
   [2,3],
   [1,2],
   [1, 3],
   []
];

The order of subarrays is not that important.

Example

Following is the code −

const arr = [1, 2, 3];
const findAllSubsets = (arr = []) => {
   arr.sort();
   const res = [[]];
   let count, subRes, preLength;
   for (let i = 0; i < arr.length; i++) {
      count = 1;
      while (arr[i + 1] && arr[i + 1] == arr[i]) {
         count += 1;
         i++;
      }
      preLength = res.length;
      for (let j = 0; j < preLength; j++) {
         subRes = res[j].slice();
         for (let x = 1; x <= count; x++) {
            if (x > 0) subRes.push(arr[i]);
            res.push(subRes.slice());
         }
      }
   };
   return res;
};
console.log(findAllSubsets(arr));

Output

Following is the console output −

[
   [], [ 1 ],
   [ 2 ], [ 1, 2 ],
   [ 3 ], [ 1, 3 ],
   [ 2, 3 ], [ 1, 2, 3 ]
]
raja
Published on 19-Jan-2021 06:25:21
Advertisements