How to create a 2D array of integers in JS?
Ray Ch
Posted on September 20, 2022
Today I was working on leetcode daily challenge using JS. There was a minor issue with Array, and I found the right way to create an array. And this is how I created the Array.
let dp = [...Array(n+1)].map(e => Array(m+1).fill(0))
Wait a minute? Give me more explanation if you ask.
I used to use.
let dp = new Array(1001)
By which I assumed even the below code would work.
let dp = new Array(1001).fill(new Array(1001).fill(0))
But when I tried, the code gave me unexpected issues.
So, I have tried using the spread operator.
Yet still, the issue isn't resolved. My code doesn't work as expected.
What's going on in the background?
To understand this, we need to understand what's happening in Array.prototype.fill
and how it works.
Fill is a prototype of Array.
The fill() method changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length). It returns the modified Array.
What does it not say here?
If the first parameter is an object, each slot in the Array will reference that object.
If you think of it helpful, but for something else, since it has the same reference.
// A single object, referenced by each slot of the array:
const arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
So, I couldn't use fill when creating a 2D array. But, I would say someday we might have a new prototype for creating 2D arrays much efficiently.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill
Note:
For that matter, always be cautious sometimes. It's not about how you write the code. It's also about how the prototypes is written using any standard prototype.
So whenever you use any prototype, you must know about them again and not take them for granted.
Posted on September 20, 2022
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.