Search code examples
javascriptarraysiteratorcombinations

How to get all possible 3 element combinations from an array of n elements in JavaScript?


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?


Solution

  • 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