Files
30-seconds-of-code/snippets/initialize-array-with-values.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

568 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Initialize array with values array flower-portrait-1 2017-12-17T17:55:51+02:00 2020-10-20T23:02:01+03:00

Initializes and fills an array with the specified values.

  • Use Array.from() to create an array of the desired length, Array.prototype.fill() to fill it with the desired values.
  • Omit the last argument, val, to use a default value of 0.
const initializeArrayWithValues = (n, val = 0) =>
  Array.from({ length: n }).fill(val);
initializeArrayWithValues(5, 2); // [2, 2, 2, 2, 2]