function combinations(arr, len) {
let tempArry = []
let final = []
for (let i = 0; i < arr.length; i++) {
console.log("i ", i)
if ((arr.length - i) == (len - 1)) {
break
}
tempArry.push(arr[i])
for (let j = i + 1; j < arr.length; j++) {
console.log("j ", j)
tempArry.push(arr[j])
console.log("tempArry ", tempArry)
if (tempArry.length == len) {
console.log("tempArry inside if ", tempArry)
final.push([...tempArry])
console.log("final inside if ", final)
tempArry.pop()
}
}
tempArry = []
}
console.log("final ", final)
return final
}
combinations([1, 2, 3, 4, 5], 3)
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter