JavaScript: Get all possible subset with a fixed length combinations in an array

JavaScript Function: Exercise-21 with Solution

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.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.

﻿