Geoff
Geoff

Reputation: 6629

Adding items to the end of an array in JavaScript/TypeScript

I have this do while loop

trucks = [];
fetchdata(){
    this.trucks = [];

    do {

     this._reportService.getReports({
        ..//pagination stuff here
        })
        .subscribe(res=> {
          this.trucks.push(res.rawdatatrucks);
        })
    } while(i<this.totalRecords);
    console.log(this.trucks)

}

THe above works but data is pushed in this form

0:[
    0:[ ...truck data stuff ],
    1:[ ...truck data stuff ],
    2:[ ...truck data stuff ],
    3:[ ...truck data stuff ],
 ],
 1:[
    0:[ ...truck data stuff ],
    1:[ ...truck data stuff ],
    2:[ ...truck data stuff ],
    3:[ ...truck data stuff ],
 ],

What i was looking forward to get is to append the data at the end of the array such that i would get

console.log(this.trucks)

     0:[ ...truck data stuff ],
    1:[ ...truck data stuff ],
    2:[ ...truck data stuff ],
    3:[ ...truck data stuff ],
    4:[ ...truck data stuff ],
    5:[ ...truck data stuff ],
    6:[ ...truck data stuff ],
    .......

A response from the server that is

console.log(res.rawdatatrucks);

always starts at 0 even in the other iterations of the while loop.

What else do i need to add to the .push method

Upvotes: 0

Views: 2485

Answers (1)

Mitch
Mitch

Reputation: 1868

Use concat instead of push.

this.trucks = this.trucks.concat(res.rawdatatrucks);

Upvotes: 3

Related Questions