skip to Main Content

I’m trying to get all the possible combinations of pairs

const arr = [1,2,3];

const groups = [];

for (let i = 0, i < arr.length, i++) {
  for (let j = i + 1, j < arr.length, j++) {
    groups.push(arr[i] + ", " + arr[j]);
  }
}

document.body.innerHTML = groups;

3

Answers


  1. You’ve used commas , instead of semicolons ; in the for loop definitions.
    The code should look like this:

    const arr = [1, 2, 3];
    
    const groups = [];
    
    for (let i = 0; i < arr.length; i++) {
      for (let j = i + 1; j < arr.length; j++) {
        groups.push(arr[i] + ", " + arr[j]);
      }
    }
    
    document.body.innerHTML = groups.join("<br>");
    
    Login or Signup to reply.
  2. The code you provided has some syntax errors in the for loops. The correct syntax for a for loop is for (initialization; condition; increment). You have used commas instead of semicolons to separate the initialization, condition, and increment parts.

    Login or Signup to reply.
  3. There are two mistakes here. The first is that the syntax is the for loop is

    for(; 😉

    and not

    for(, ,)

    Secondly, in the seond for loop, you initalized j, as

    let j = i + 1

    However, if you would like all possible combinations, then it j should be 0 instead.

    So you would have:

    for (let i = 0; i < arr.length; i++) {
      for (let j = 0; j < arr.length; j++) {
        console.log(arr[i] + ", " + arr[j]);
      }
    }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search