Introduction
In this lab, we will explore how to initialize and fill an array with specified values using a mapping function in JavaScript. We will be using the Array() constructor to create an array of the desired length and the Array.prototype.fill() method to fill it with null values. Additionally, we will be using the Array.prototype.map() method to fill the array with the desired values using the provided function.
Initializing a Mapped Array in JavaScript
To initialize a mapped array in JavaScript, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
Array()constructor to create an array of the desired length. - Use
Array.prototype.fill()to fill the array withnullvalues. - Use
Array.prototype.map()to fill the array with the desired values, using the provided function,mapFn. - Omit the second argument,
mapFn, to map each element to its index.
Here's an example code snippet:
const initializeMappedArray = (n, mapFn = (_, i) => i) =>
Array(n).fill(null).map(mapFn);
You can use the initializeMappedArray function to create a mapped array with the desired values:
initializeMappedArray(5); // [0, 1, 2, 3, 4]
initializeMappedArray(5, (i) => `item ${i + 1}`);
// ['item 1', 'item 2', 'item 3', 'item 4', 'item 5']
Summary
Congratulations! You have completed the Initialize Mapped Array lab. You can practice more labs in LabEx to improve your skills.