Angular -How to display or loop though array of arrays

39 views Asked by At

I would like to display the list of arrays that contain arrays inside.

I have arrays as below with dummy data

[
    [
        {
            "date": "September 11",
            "User": "ABC",
            "Action": "Added"
            
        },
        {
            "date": "September 11",
            "User": "asd",
            "Action": "Removed"
            
        }
    ],
    [
        {
            "date": "September 8",
            "User": "sdf",
            "Action": "Added"
            
        },
        {
            "date": "September 8",
            "User": "rty",
            "Action": "Updated"
           
        },
        {
            "date": "September 8",
            "User": "pol",
            "Action": "Removed"           
        }
    ]
]

I am trying to get data as below with angular mat table in the html page based on the date

September 11

  • ABC Added

  • asd Removed

September 8

  • sdf Added

  • rty Updated

  • pol Removed

2

There are 2 answers

0
Jeresava On

You can iterate through each items in the list (so every events of the same date). Then, once inside you can loop another time through every event of said date.

Basically, you only need two loops.

Here's an example with a console.log() in javascript with the data you provided:

let i = 0;
let j = 0;
let date = "";

for (i = 0; i<array.length; i++){
    for (j=0; j < array[i].length; j++){
        if (date == ""){
           date = array[i][j]['date'];
           console.log(array[i][j]['date']);
        }
        console.log(array[i][j]['User'] + " " + array[i][j]['Action']);
    }
date = "";
}

And the result:

enter image description here

Cheers!

0
José Matos On

You could try something like this:

<div *ngFor="let dataArray of data">
  <div *ngIf="dataArray.length > 0">
    <h2>{{ dataArray[0].date }}</h2>
    <table>
      <tr *ngFor="let item of dataArray">
        <td>{{ item.User }}</td>
        <td>{{ item.Action }}</td>
      </tr>
    </table>
  </div>
</div>