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 with null 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']

More like this

  • JavaScript Array Initialization

    Discover the inner workings of JavaScript arrays and learn about the different ways to initialize them.

    Collection · 9 snippets

  • Initialize array until

    Initializes and fills an array with values generated by a function, until a condition is met.

    JavaScript, Array · Jun 22, 2023

  • Initialize array while

    Initializes and fills an array with values generated by a function, while a condition is met.

    JavaScript, Array · Jun 20, 2023

  • Initialize array with values

    Initializes and fills an array with the specified values.

    JavaScript, Array · Oct 20, 2020