Published on

Javascript Create multidimensional Array initialized with 0.

Authors

Multidimention are required while solving complex problem using memoization. In there is no native support for Multidimensional array. Using ES6 one-line code we can create 2D, 3D, etc.

Create 2D array initialized with 0

In this example, we will create 10*10 array initialized with 0. We will use ES6 array method fill().

// This code will create a 10*10 arrray initialized with 0
const multiDimentionalArray = Array.from(Array(10), () => new Array(10).fill(0))
console.log(multiDimentionalArray[0][0]) //0
console.log(multiDimentionalArray[1][0]) // 0
console.log(multiDimentionalArray[9][5]) // 0
//Generalised code n*m filled with val
const multiDimentionalArray = Array.from(Array(n), () => new Array(m).fill(val))