Created
November 5, 2023 15:49
-
-
Save FredLackeyOfficial/0b3eff616aa7f45a315dacd062f8ebc4 to your computer and use it in GitHub Desktop.
Simple JavaScript method to return all possible combinations from a given array.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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