Convert loop to .map()pro

Convert a loop with .push() into a .map() call.

Refactoring (Convert)
ES5
P42 for VS Code
Pro & Business
Convert loop to .map()

The anArray.map(aFunction) function creates a new array that contains a transformed value for each original array element. It can be used to replace patterns where a value is calculated for each array element and then pushed into a new array.

For example,

const values = [];
for (const element of elements) {
  values.push(f(element));
}

becomes

const values = elements.map((element) => {
  return f(element);
});

When there is an inner spread expression, the refactoring converts to anArray.flatMap:

const values = [];
for (const element of elements) {
  values.push(...element);
}

becomes

const values = elements.flatMap((element) => {
  return element;
});

The refactoring works on regular for loops, for..of loops, and .forEach calls.

Configuration

Related Code Assists

Learn More

Available In