1

Suppose I have the below array of integers in JavaScript:

[5,7,6,1,7,5,4,8,2,4]

And I want to create a function that extracts all possible 3 element combinations from it, like below:

[[5,7,6],[5,7,1],[5,7,7],etc]

What is the most performant and shortest way to do it?

Is there a better way to do it than for loops?

iamaprogrammer
  • 115
  • 3
  • 10
  • Do you mean [combinations](https://en.wikipedia.org/wiki/Combination) according to their mathematical definition? The important question being whether repetitions are allowed and whether the order does matter? – Mushroomator Apr 25 '22 at 10:30
  • Does this answer your question? [Algorithm to return all combinations of k elements from n](https://stackoverflow.com/questions/127704/algorithm-to-return-all-combinations-of-k-elements-from-n) – Mushroomator Apr 25 '22 at 10:51

1 Answers1

2

I think the simplest and most performant way to do it is for loops like this

const data = [5,7,6,1,7,5,4,8,2,4]

const combinations = []

for(let i = 0; i < data.length -2; i++){
  for(let j = i + 1; j < data.length -1; j++){
    for(let k = j + 1; k < data.length; k++){
       combinations.push([data[i],data[j],data[k]])
    }
  }
}

console.log(combinations)

There are more elegant ways to do it but less performant

R4ncid
  • 6,944
  • 1
  • 4
  • 18