0

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*/
    }
}
1
  • 2
    Please the post example array Commented Mar 11, 2019 at 17:58

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

4 Comments

what if I want to get the data based on the row instead of cell? Supposing each array within the parent array is a row from database
@ErrolChavesMoya can you explain your use case a little bit more, I think there is some confusion here on what you want to achieve
@chairmanmow thanks, it woked. But I had to modify your answer to do what I wanted
@moronator nevermind I solved it already Thanks for your help. I just had to remove the second forEach of this answer to make it work like this: link
1

Since you didn't provide an example array, it's hard to help with your specific problem but assuming you have a n-dimensional array it could look something like this:

var DetalleFactura=[0, [1, 2, 3], [4, 5, [6, 7, 8]]]

function printArray(arr){
  for(var item of arr){
    if(typeof(item) == 'object') printArray(item)
    else console.log(item)
  }
}
printArray(DetalleFactura)

If you want to learn more about for-loops like this you may read this mozilla article

4 Comments

It is not two-dimensional it can be whatever dimension the user want.
Then you should take a look at recursion
Edited to print a n-dimensional array now
what if I want to get the data based on the row instead of cell? Supposing each array within the parent array is a row from database

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.