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:
Flowchart: JavaScript function: Get all possible subset with a fixed length combinations in an arrayLive 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.
For more Practice: Solve these Related Problems:
- Write a JavaScript function that generates all subsets of an array with a fixed length using a recursive approach.
- Write a JavaScript function that returns all unique combinations of a specified length from an array.
- Write a JavaScript function that generates fixed-length subsets and sorts each subset before adding it to the final result.
- Write a JavaScript function that computes fixed-length subsets from an array without resorting to built-in combinatorics libraries.
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.