Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Only trigger a function in the last iteration of a forEach loop

The following code checks if a field is of type file and if there's an actual file in it. If that's the case, upload the photo and update the buildings. If that's not the case, update the building using the old photos:

  fields.forEach(field => {
    building[field.name] = field.value || this.building[field.name]
    if (field.type === 'file' && !util.isEmpty(field.photo.file)) {
      api.uploadPhoto(field.photo.file).then(resp => {
        building[field.name] = resp
        this.updateBuilding(building)
      })
    } else {
      building.logo = this.building.logo // to prevent updating logo
      building.floorplan = this.building.floorplan // to prevent updating logo
      this.updateBuilding(building)
    }
  })

It works well, but since this.updateBuilding(building) is in a loop, it's being called multiples.

How to do it so it's only called in the last iteration?

like image 880
alex Avatar asked Nov 20 '25 08:11

alex


2 Answers

The MDN documentation suggest that the callback to forEach has three arguments:

  1. The element value
  2. The element index
  3. The array being traversed

You can use it to check whether the current element's index is equal to the last index of the array:

fields.forEach((field, index, array) => {

  // YOUR CODE

  if (index === array.length - 1) {
    // DO SOMETHING
  }
});
like image 195
Soubhik Mondal Avatar answered Nov 22 '25 21:11

Soubhik Mondal


You can check fields.length of fields array and it will be last element of fields array.

if(fields[fields.length - 1]){
 // Loop control will enter in this block in last iteration
 // Enter your update code inside this
}

Hope this is what you were looking for.

like image 35
Kapil Yadav Avatar answered Nov 22 '25 21:11

Kapil Yadav