Published
Edited
Dec 10, 2021
2 stars
Insert cell
# Combinations
Insert cell
function getCombinations(arr, numberToSelect) {
const results = [];
if (numberToSelect === 1) return arr.map((el) => [el]);

for (const [index, fixedVal] of Object.entries(arr)) {
const rest = arr.slice(Number(index) + 1);
const combinations = getCombinations(rest, numberToSelect - 1);
const attached = combinations.map((el) => [fixedVal, ...el]);
results.push(...attached);
}

return results;
};

Insert cell
getCombinations([1, 2, 3, 4], 3);
Insert cell

Purpose-built for displays of data

Observable is your go-to platform for exploring data and creating expressive data visualizations. Use reactive JavaScript notebooks for prototyping and a collaborative canvas for visual data exploration and dashboard creation.
Learn more