1

I thought initializing an multi dimensional array would be easy:

row = Array(4).fill(0)
block = Array(4).fill(row)
block[2][2] = 15

but that just creates an array of one row, 4 times, so if I assign block[2][2] = 15, then the whole column is 15.

(4) [Array(4), Array(4), Array(4), Array(4)]
0:(4) [0, 0, 15, 0]
1:(4) [0, 0, 15, 0]
2:(4) [0, 0, 15, 0]
3:(4) [0, 0, 15, 0]

I tried Array(4).fill(Array(4).fill(0)) but had the same result.

2
  • 3
    JavaScript is pass by reference, not value. So when you fill the block array with row, you're assigning the same object to every index. Commented Mar 19, 2018 at 0:54
  • got it, same row, 4 times. Commented Mar 19, 2018 at 0:56

2 Answers 2

2

You could write a helper function to initialize your two dimensional array. For example:

const grid = (r, c) => Array(r).fill(null).map(r => Array(c).fill(null));

const g = grid(4, 4);
g[2][2] = 15;

console.log(g);

Sign up to request clarification or add additional context in comments.

1 Comment

that works good. Seems harder than it s/b, but I'll take it. Thanks!
0

This was actually quite challenging to solve. I much prefer the accepted answer from fubar - however I thought I would add another possibility for some variance.

Pro: Doesn't obfuscate that you are dealing with an Array (like with the accepted answer).

Con: Hard to read.

var row = new Array(4).fill(0)
var block = new Array(4).fill(0).map(v => deepClone(row))
block[2][2] = 15
console.log(block);

function deepClone(array){return JSON.parse(JSON.stringify(array));}

How does this work? Well after you fill the array with blank values, .map is now able to iterate each and replace the value. In this case, it is a hacky deep clone of row thanks to the trusty ole JSON.parse.

1 Comment

This will only work with native objects and primitives. If you use a self defined class, it'll lose it's type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.