skip to Main Content
const listOfNeighbours = [
  ["Canada", "Mexico"],
  ["Spain"],
  ["Norway", "Sweden", "Russia"],
];

for (let i = 0; i < listOfNeighbours.length; i++) {
  for (let j = 0; j < listOfNeighbours[j].length; j++) {
    console.log(`Neighbours : ${listOfNeighbours[i][j]}`);
  }
}
Neighbours : Canada
Neighbours : Spain
Neighbours : Norway

In this question only first ones are printed . How to write all of them to console log

I want like this below in order


Neighbours : Canada
Neighbours : Mexico
Neighbours : Spain
Neighbours : Norway
Neighbours : Sweden
Neighbours : Russia

3

Answers


  1. Your inner loop is only going to listOfNeighbours[j], using j, which is the current iterator. Us i as the index for listOfNeighbors in the inner loopfor (let j = 0; j < listOfNeighbours[i].length; j++) {

    const listOfNeighbours = [
      ["Canada", "Mexico"],
      ["Spain"],
      ["Norway", "Sweden", "Russia"],
    ];
    
    for (let i = 0; i < listOfNeighbours.length; i++) {
      for (let j = 0; j < listOfNeighbours[i].length; j++) {
        console.log(`Neighbours : ${listOfNeighbours[i][j]}`);
      }
    }
    Login or Signup to reply.
  2. you can also use flat(), which simplifies the syntax.

    const listOfNeighbours = [
    ["Canada", "Mexico"],
      ["Spain"],
      ["Norway", "Sweden", "Russia"],
    ].flat();
    
    for (let i = 0; i < listOfNeighbours.length; i++) {
     
        console.log(`Neighbours : ${listOfNeighbours[i]}`);
      
    }
    
    Login or Signup to reply.
  3. It’s not with for loop but you will get the same result:

    const listOfNeighbours = [
      ["Canada", "Mexico"],
      ["Spain"],
      ["Norway", "Sweden", "Russia"],
    ];
    listOfNeighbours
      .flat()
      .forEach(element =>
        console.log(`Neighbours : ${ element }`)
      );
    .as-console-wrapper { min-height: 100%!important; top: 0; }
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search