how to combine two numbers between an array of numbers with javascript?

Issue

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]
]

Solution

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);

Answered By – akicsike

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published