JavaScript: Get all possible subset with a fixed length combinations in an array
JavaScript Function: Exercise-21 with Solution
Fixed-Length Subsets
Write a JavaScript function to get all possible subsets with a fixed length (for example 2) combinations in an array.
Sample array : [1, 2, 3] and subset length is 2
Expected output : [[1,2],[1,3],[2,3]]
Sample Solution:
JavaScript Code:
// Function to get all possible subsets with a fixed length
function getSubsetsWithLength(arr, length) {
const result = [];
// Recursive function to generate subsets
function generateSubsets(currentSubset, start) {
if (currentSubset.length === length) {
result.push([...currentSubset]); // Add a copy of the currentSubset to the result
return;
}
for (let i = start; i < arr.length; i++) {
currentSubset.push(arr[i]);
generateSubsets(currentSubset, i + 1);
currentSubset.pop();
}
}
generateSubsets([], 0);
return result;
}
// Example usage:
const inputArray = [1, 2, 3];
const subsetLength = 2;
const resultSubsets = getSubsetsWithLength(inputArray, subsetLength);
// Log the result to the console
console.log(resultSubsets);
Output:
[[1,2],[1,3],[2,3]]
Flowchart:
Live Demo:
See the Pen JavaScript - Get all possible subset with a fixed length combinations in an array-function-ex- 21 by w3resource (@w3resource) on CodePen.
Improve this sample solution and post your code through Disqus.
Previous: Write a JavaScript function that generates a string id (specified length) of random characters.
Next: Write a JavaScript function that accepts two arguments, a string and a letter and the function will count the number of occurrences of the specified letter within the string.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://www.w3resource.com/javascript-exercises/javascript-function-exercise-21.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics