• 0

Multi dimensional arrays in javascript

Problem description :

The following function creates a 2-D array and initialize it with zeros. Find a bug in the code and propse a solution to it.

The following gist shows the given code to create 2-D arrays with a bug and shows an example showing the problem in the code.


Solution :

Issue in the above code is that the values are being referenced, they are not being copied. Hence, setting matrix[0][0] = 89; will update matrix[1][0] = matrix[2][0] = 89

Following gist shows one possible way of creating 2-D array in javascript.


In the above code the values are being copied. Hence, setting matrix[0][0] = 89; will not update matrix[1][0] and matrix[2][0]. The values for matrix[1][0] = matrix[2][0] = 0


Solution 2: You can wrap things inside a new function and return 1-D array as shown below.


PS: Always remember the basics of pass by value vs pass by reference.