const combinations = (arr, num) => {
const result = [];
const comb = (arr, n, idx, cur) => {
for (let i = idx; i <= arr.length - n; i += 1) {
cur.push(arr[i]);
if (n === 1) {
result.push([...cur]);
} else {
comb(arr, n - 1, i + 1, cur);
}
cur.pop();
}
};
comb(arr, num, 0, []);
return result;
}
console.log(combinations([1, 2, 3, 4], 3));
// Array(4) [ (3) […], (3) […], (3) […], (3) […] ]
// 0: Array(3) [ 1, 2, 3 ]
// 1: Array(3) [ 1, 2, 4 ]
// 2: Array(3) [ 1, 3, 4 ]
// 3: Array(3) [ 2, 3, 4 ]
// length: 4