Home > OS >  how to combine two numbers between an array of numbers with javascript? [duplicate]
how to combine two numbers between an array of numbers with javascript? [duplicate]

Time:09-24

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

CodePudding user response:

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

  • Related