javascriptarraysloops

Loop through array with arrays using Javascript


I have a var which contains an array with multiple arrays. I am trying to get the values of each cell to print them into an HTML table.

I want to use a foreach but since I have no idea how to do it, even though I've seen examples on the internet, I tried to do this using a for loop but cannot make it work.

Is there an easier way to do this?

This is the code I have:

var DetalleFactura = response[0]['DetalleFactura']; //var with the array I'd like to print

for (let i = 0; i < DetalleFactura.length; i++) {
    var value = parent[i];
    for (let j = 0; j < parent[i].length; j++) {
        /*print values here*/
    }
}

Solution

  • Per your question here's how you can print the values like you indicated using forEach.

    DetalleFactura.forEach((subArr)=>{
    subArr.forEach(val => {
    console.log(val);
       })
    });
    

    You can also just use array.flat() to get the results you want.

    const flatArr = DetalleFactura.flat();
    

    Array.prototype.flat documentation