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

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
- Code Assist ID (for the configuration file):
convert-loop-to-map
- You can configure custom keyboard shortcuts with this code action kind:
refactor.convert.p42.convert-loop-to-map