Initialize mapped array
JavaScript, Array · Jun 13, 2023

Initializes and fills an array with the specified values, using a mapping function.
- Use the
Array()
constructor to create an array of the desired length. - Use
Array.prototype.fill()
to fill it withnull
values. - Use
Array.prototype.map()
to fill it with the desired values, using the provided function,mapFn
. - Omit the second argument,
mapFn
, to map each element to its index.
const initializeMappedArray = (n, mapFn = (_, i) => i) =>
Array(n).fill(null).map(mapFn);
initializeMappedArray(5); // [0, 1, 2, 3, 4]
initializeMappedArray(5, i => `item ${i + 1}`);
// ['item 1', 'item 2', 'item 3', 'item 4', 'item 5']
Written by Angelos Chalaris
I'm Angelos Chalaris, a JavaScript software engineer, based in Athens, Greece. The best snippets from my coding adventures are published here to help others learn to code.
If you want to keep in touch, follow me on GitHub.