Introduction
In this lab, we will explore how to create n-dimensional arrays with a given value using recursion in JavaScript. We will use the Array.from() and Array.prototype.map() methods to generate rows where each is a new array initialized using initializeNDArray(). By the end of this lab, you will have a solid understanding of how to create multi-dimensional arrays in JavaScript and how to use recursion to accomplish this task.
How to Initialize an N-Dimensional Array in JavaScript
To create an N-dimensional array in JavaScript, you can use the initializeNDArray function. This function takes a value and any number of dimensions as arguments and returns a new array initialized with that value.
To use initializeNDArray, you can follow these steps:
- Open the Terminal/SSH and type
nodeto start coding. - Use recursion to create the array with the given number of dimensions.
- Use
Array.from()andArray.prototype.map()to generate rows where each row is a new array initialized usinginitializeNDArray().
Here's the code for the initializeNDArray function:
const initializeNDArray = (val, ...args) =>
args.length === 0
? val
: Array.from({ length: args[0] }).map(() =>
initializeNDArray(val, ...args.slice(1))
);
You can then call initializeNDArray with the desired value and number of dimensions. For example:
initializeNDArray(1, 3); // [1, 1, 1]
initializeNDArray(5, 2, 2, 2); // [[[5, 5], [5, 5]], [[5, 5], [5, 5]]]
Summary
Congratulations! You have completed the Initialize N-Dimensional Array lab. You can practice more labs in LabEx to improve your skills.