skip to Main Content

What is the best way to iterate a multidivisional array using forEach JavaScript Google script?

I came up with this.

values.forEach(function(row){
  values[0].forEach(function(_,col){
    console.log(row[col])
  });
});

While it works I have a feeling there is a better way to write it

2

Answers


  1. You can directly call forEach on the inner array:

    let values = [[1,2,3], [4,5,6]];
    values.forEach(row => row.forEach(x => {
      console.log(x);
    }));
    Login or Signup to reply.
  2. You can iterate directly over row:

    values.forEach(function (row) {
      row.forEach(function(col) {
        console.log(col);
      });
    });
    

    Alternatively, you can use arrow functions and make it into a one-liner:

    values.forEach(row => row.forEach(col => console.log(col)));
    

    You could also use a for..of loop:

    for (const row of values) {
      for (const col of row) {
        console.log(col);
      }
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search