

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Finding all possible subsets of an array in JavaScript
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 ] ]
- Related Questions & Answers
- Finding all possible combinations from an array in JavaScript
- Maximum possible difference of two subsets of an array in C++
- Sum of XOR of all possible subsets in C++
- Finding all possible ways of integer partitioning in JavaScript
- Sum of the products of all possible Subsets in C++
- Generating all possible permutations of array in JavaScript
- Take an array of integers and create an array of all the possible permutations in JavaScript
- Finding all the longest strings from an array in JavaScript
- Finding all peaks and their positions in an array in JavaScript
- Finding the rotation of an array in JavaScript
- Finding the mid of an array in JavaScript
- Finding degree of subarray in an array JavaScript
- Finding all possible combined (plus and minus) sums of n arguments JavaScript
- Finding the index position of an array inside an array JavaScript
- Finding all duplicate numbers in an array with multiple duplicates in JavaScript
Advertisements