alex alex - 1 year ago 57
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.value || this.building[]
if (field.type === 'file' && !util.isEmpty( {
api.uploadPhoto( => {
building[] = resp
} else {
building.logo = this.building.logo // to prevent updating logo
building.floorplan = this.building.floorplan // to prevent updating logo

It works well, but since
is in a loop, it's being called multiples.

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

Answer Source

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) => {


  if (index === array.length - 1) {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download