Initialize Mapped Array

JavaScriptJavaScriptBeginner
Practice Now

This tutorial is from open-source community. Access the source code

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.


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL javascript(("`JavaScript`")) -.-> javascript/BasicConceptsGroup(["`Basic Concepts`"]) javascript(("`JavaScript`")) -.-> javascript/AdvancedConceptsGroup(["`Advanced Concepts`"]) javascript/BasicConceptsGroup -.-> javascript/variables("`Variables`") javascript/BasicConceptsGroup -.-> javascript/data_types("`Data Types`") javascript/BasicConceptsGroup -.-> javascript/arith_ops("`Arithmetic Operators`") javascript/BasicConceptsGroup -.-> javascript/comp_ops("`Comparison Operators`") javascript/AdvancedConceptsGroup -.-> javascript/higher_funcs("`Higher-Order Functions`") javascript/AdvancedConceptsGroup -.-> javascript/template_lit("`Template Literals`") subgraph Lab Skills javascript/variables -.-> lab-28396{{"`Initialize Mapped Array`"}} javascript/data_types -.-> lab-28396{{"`Initialize Mapped Array`"}} javascript/arith_ops -.-> lab-28396{{"`Initialize Mapped Array`"}} javascript/comp_ops -.-> lab-28396{{"`Initialize Mapped Array`"}} javascript/higher_funcs -.-> lab-28396{{"`Initialize Mapped Array`"}} javascript/template_lit -.-> lab-28396{{"`Initialize Mapped Array`"}} end

Initializing a Mapped Array in JavaScript

To initialize a mapped array in JavaScript, follow these steps:

  1. Open the Terminal/SSH and type node to start practicing coding.
  2. Use the Array() constructor to create an array of the desired length.
  3. Use Array.prototype.fill() to fill the array with null values.
  4. Use Array.prototype.map() to fill the array with the desired values, using the provided function, mapFn.
  5. 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.

Other JavaScript Tutorials you may like