
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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 ] ]
Advertisements