Initialize 2D 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 a 2D array in JavaScript. We will use the Array.from() and Array.prototype.map() methods to create an array of given width and height, and fill it with a specified value. This lab will provide a hands-on experience of working with 2D arrays and understanding their implementation in JavaScript.


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/destr_assign("`Destructuring Assignment`") subgraph Lab Skills javascript/variables -.-> lab-28390{{"`Initialize 2D Array`"}} javascript/data_types -.-> lab-28390{{"`Initialize 2D Array`"}} javascript/arith_ops -.-> lab-28390{{"`Initialize 2D Array`"}} javascript/comp_ops -.-> lab-28390{{"`Initialize 2D Array`"}} javascript/higher_funcs -.-> lab-28390{{"`Initialize 2D Array`"}} javascript/destr_assign -.-> lab-28390{{"`Initialize 2D Array`"}} end

Initializing a 2D Array in JavaScript

To initialize a 2D array in JavaScript, you can use the following code:

const initialize2DArray = (width, height, value = null) => {
  return Array.from({ length: height }).map(() =>
    Array.from({ length: width }).fill(value)
  );
};

This code uses Array.from() and Array.prototype.map() to create an array of height rows, where each row is a new array of width length. It also uses Array.prototype.fill() to set all items in the array to the value parameter. If no value is provided, it defaults to null.

You can call the function like this:

initialize2DArray(2, 2, 0); // [[0, 0], [0, 0]]

This will create a 2D array with width of 2, height of 2, and all values set to 0.

Summary

Congratulations! You have completed the Initialize 2D Array lab. You can practice more labs in LabEx to improve your skills.

Other JavaScript Tutorials you may like