Initialize 2D Array

Beginner

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.

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.