Skip to content
Advertisement

how to keep track of objects inserted in an array

When clicking add it should keep inserting object to the array and the order Id should be based from the current order id + 1 of the objects on the array so for example if if templatesDto is empty then every order in the object should increment starting from 0 when I click add

but for example there are existing data on the templatesDto example

[
    {
        "id": 255,
        "order": 0,

    },
    {
        "id": 256,
        "order": 1,
    },
     {
        "id": 256,
        "order": 2,
    },
]

then if I click add the next order value of the new added object should be 3 since the last one is 2.

Any idea guys ? Thank you.

#html code

 <button (click)="add()" mat-stroked-button mat-button class="btn-add-entitlement action-btn">
                <mat-icon aria-label="Add" class="add-icon">add</mat-icon> Add 
            </button>

#ts code – to insert object to array

   this.templatesDto= []
    
      add() {
        this.templatesDto.push({
          id: 0,
          order : 0,
        })
      }

#sample result if I click add and there are no data in templatesDto

[
    {
        "id": 0,
        "order": 0,
    },
    {
        "id": 0,
        "order": 1,
    },
    {
        "id": 0,
        "order": 2,
    }
    ....
]

Advertisement

Answer

Set order to call getNextOrder() with the function being:

function getNextOrder() {
    if (this.templatesDto.length === 0) {
        return 0
    }

    let maxOrder = 0
    for (const template of this.templatesDto) {
        if (template.order > maxOrder) {
            maxOrder = template.order
        }
    }
    return maxOrder + 1
}

This function goes through all objects in the array, gets the highest order value and then returns it incremented by 1.

This should also work, even if the objects in the array are not ordered according to the order property.

User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement