skip to Main Content

I’ve this array in JS:

datas = [
    ["Elem1", "Data1"],
    ["Elem2", "Data2"],
    ["Elem3", "Data3"]
];

I’m using:

datas.forEach((element, index) => {
  alert(element.Elem1);
});

But it don’t work.

How I can loop to get each result ?

Thanks.

3

Answers


  1. Yes, It’s simple.

    Option 1: Simple For Loops

    for (let i = 0; i < data.length; i++) {
      for (let j = 0; j < data[i].length; j++ {
        console.log(datas[i][j]);
      }
    }
    

    Option 2: For of

    for (const row of datas) {
     for (cost field of row) {
       console.log(field);
     }
    }
    

    Option 3: Array.prototype.forEach

    datas.forEach(row => {
      row.forEach(field => {
        console.log(field);
      })
    });
    

    There are more exciting ways to try, read the MDN Documentation to get more info.

    Login or Signup to reply.
  2. The provided array is a two-dimensional array, where each element is an array itself containing two values. To access the values within each subarray, you need to use indices rather than object properties.

    To loop through the array and retrieve each value, you can modify your code as follows:

    datas.forEach((element, index) => {
      alert(element[0]); // Access the first value in the subarray
    });
    

    This will display "Elem1", "Elem2", and "Elem3" in separate alert dialogs. If you want to access the second value in each subarray, you can use element[1] instead.

    Remember that indices in JavaScript start from 0, so element[0] retrieves the first value in each subarray.

    If you want to loop all the children dynamically, you do like the following:

    datas.forEach((element, index) => {
      element.forEach((element2, index2) => {
        alert(element2);
      });
    });
    
    Login or Signup to reply.
  3. You can flatten the array and use a simple loop:

    for (const element of datas.flat()) {
      console.log(element)
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search