0

I have an array of numbers and would like to generate all possible combinations with 2 numbers as shown in the expected

const numbers = [1,2,3];

Expected:

const result = [
  [1,2],
  [1,3],
  [2,1],
  [2,3],
  [3,1],
  [3,2]
]
  • Does this answer your question? [Permutations in JavaScript?](https://stackoverflow.com/questions/9960908/permutations-in-javascript) – kks21199 Sep 23 '21 at 19:38

1 Answers1

2

let num = [1,2,3];
let arr = [];

for(let i=0; i<num.length; i++){

  for(let j=0; j<num.length; j++){
    if(j === i) continue;
    arr.push([num[i], num[j]]);
  }

}

console.log(arr);
akicsike
  • 371
  • 2
  • 8