alex alex - 29 days ago 7
Javascript Question

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?

Answer

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
  }
});