Published
Edited
Dec 10, 2021
1 star
Insert cell
# Permutations
Insert cell
function getPermutations (arr, numberToSelect) {
const permutations = [];
if (numberToSelect === 1) return arr.map((el) => [el]);

for (const [index, fixedVal] of Object.entries(arr)) {
const rest = [...arr.slice(0, +index), ...arr.slice(+index + 1)];
const childPermutations = getPermutations(rest, numberToSelect - 1);
const attached = childPermutations.map((el) => [fixedVal, ...el]);
permutations.push(...attached);
}

return permutations;
};
Insert cell
getPermutations([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