Skip to content

Instantly share code, notes, and snippets.

@FredLackeyOfficial
Created November 5, 2023 15:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FredLackeyOfficial/0b3eff616aa7f45a315dacd062f8ebc4 to your computer and use it in GitHub Desktop.
Save FredLackeyOfficial/0b3eff616aa7f45a315dacd062f8ebc4 to your computer and use it in GitHub Desktop.
Simple JavaScript method to return all possible combinations from a given array.
const generateCombinations = (arr, length) => {
if (length === 0) return [[]];
if (arr.length === 0 || length > arr.length) return [];
if (length === 1) return arr.map(item => [item]);
const combinations = [];
for (let i = 0; i < arr.length; i++) {
const withoutCurrent = arr.slice(i + 1);
const current = arr[i];
const smallerCombinations = generateCombinations(withoutCurrent, length - 1);
const combined = smallerCombinations.map(item => [current, ...item]);
combinations.push(...combined);
}
return combinations;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment