How to use Array.from with a Mapping Function In Javascript
Using Array.from with a mapping function, you can create an array of a specific length with pre-filled values. The mapping function defines the values to fill the array. This approach offers concise and flexible syntax for generating arrays with custom initial values.
Example: In this example we generates a new array filledArray of length 5, filled with the value 0 using Array.from() and an arrow function. It then logs filledArray to the console.
const length = 5;
const value = 0;
const filledArray = Array.from({ length }, () => value);
console.log(filledArray);
Output
[ 0, 0, 0, 0, 0 ]
JavaScript Program to Create an Array with a Specific Length and Pre-filled Values
In JavaScript, we can create an array with a specific length and pre-filled values using various approaches. This can be useful when we need to initialize an array with default or placeholder values before populating it with actual data.
Table of Content
- Using the Array() Constructor and fill() Method
- Using a Loop to Initialize Values
- Using the map() Method
- Using Array.from with a Mapping Function