Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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,
    }
    ....
]

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading