Categories
JavaScript Answers

How to Create a Two-Dimensional Array in JavaScript?

Spread the love

Sometimes we’ve to create a 2-dimensional array in a JavaScript app.

In this article, we’ll look at how to create 2-dimensional arrays with JavaScript.

Nested Arrays

In JavaScript, 2-dimensional arrays are just nested arrays.

For instance, we can write:

const arr = [
  [1, 2],
  [3, 4],
  [5, 6]
];
console.log(arr[0][0]);
console.log(arr[0][1]);
console.log(arr[1][0]);
console.log(arr[1][1]);
console.log(arr);

We have arrays in an array.

Then we can access the nested items with square brackets.

The first console log logs 1.

The 2nd console log logs 2.

The 3rd console log logs 3.

And the last console log logs 4.

Create an Empty Two Dimensional Array

To create an empty 2-dimensional array, we can use the Array.from and Array constructors.

For instance, we can write:

const arr = Array.from(Array(2), () => new Array(4))
console.log(arr);

The Array.from method lets us create an array from another array.

The first argument is the array we want to derive from the new array from.

And the 2nd argument is a function that maps the values from the first array to the values we want.

We return an array with 4 items.

Therefore, we get a 2×4 2-dimensional array returned.

Also, we can create a 2-dimensional array with just the Array function.

For instance, we can write:

const arr = Array(2).fill().map(() => Array(4));
console.log(arr);

We call the fill method to fill the empty slots.

This way, we can call map to and return arrays in the map callback to create the 2-dimensional array.

Conclusion

We can create JavaScript 2–dimensional arrays by nesting array literals.

Also, we can create 2-dimensional arrays with the Array function.

Leave a Reply

Your email address will not be published. Required fields are marked *