Fill Missing JavaScript Array Values from the Previous Row

To carry missing values forward, keep one last-known value for each field while mapping the input into a new array. Use nullish coalescing so only null and undefined are replaced; zero, false, and an empty string remain valid data.

Last updated: October 5, 2026.

function fillMissingDimensions(rows) {
  let lastWidth;
  let lastHeight;

  return rows.map((row, index) => {
    lastWidth = row.width ?? lastWidth;
    lastHeight = row.height ?? lastHeight;

    if (lastWidth === undefined || lastHeight === undefined) {
      throw new Error(`Row ${index} has no earlier value to inherit`);
    }

    return { ...row, width: lastWidth, height: lastHeight };
  });
}

const filled = fillMissingDimensions([
  { width: 32, height: 32 },
  { width: null, height: 64 },
  { width: 64 },
  { width: null, height: undefined },
]);

The function leaves the original objects unchanged and returns new ones. Width and height have independent history, so a missing width inherits the preceding width rather than whichever numeric value happened to appear most recently in another field.

Define what should happen at the start

The first row cannot inherit a value that has never appeared. Decide whether that is invalid input, whether a caller-supplied default should be used, or whether the field should remain missing. The example throws an error so incomplete leading data is not silently accepted.

MDN’s nullish coalescing reference explains why ?? differs from ||. Using row.width || lastWidth would incorrectly replace a legitimate width of zero.

Return transformed data from map

map() is appropriate because every input row produces one output row. Its callback closes over the last-known state, updates that state, and returns the normalized record. MDN’s Array.prototype.map() guide documents the new-array behavior.

If gaps should be filled independently within groups, reset the saved values whenever the group key changes, or group the rows before this pass. Continue with JavaScript arrays, loops and iteration, and reusable functions.

Related Web Cheat Sheet guides

Sergey Kornilov

Sergey Kornilov