1

I am trying to set a single value in a two dimensional array, but its not working.

Consider the following code taken from the many examples on the subject:

// create a 3x3 array with -1 in every position:
let a = new Array(3).fill(new Array(3).fill(-1))
console.log(`a: ${JSON.stringify(a)}`)
a[1][2] = 0
console.log(`a: ${JSON.stringify(a)}`)

The output is as follows:

a: [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
a: [[-1,-1,0],[-1,-1,0],[-1,-1,0]]

As we can see, instead of setting a single cell, it as actually set 3 positions in the array to 0, i.e. it sets [0][2] and [1][2] and [2][2] = 0. Very odd.

I tried this:

let a = new Array(3).fill(new Array(3).fill(-1))
console.log(`a: ${JSON.stringify(a)}`)
a[1,2] = 0
console.log(`a: ${JSON.stringify(a)}`)

Which gives the even stranger result:

a: [[-1,-1,-1],[-1,-1,-1],[-1,-1,-1]]
a: [[-1,-1,-1],[-1,-1,-1],0]

Am I going crazy, or does javascript not support setting a value in a 2 dimensional array?

2 Answers 2

6

First question

That's because you fill the outer array with the same subarray! a[0], a[1] and a[2] are all the same array! Because in JS objects (including arrays) are passed around using their references! What array.fill does is taking a parameter (in this case a reference to an array) and assigns it to every item in the array. It's like this:

var sub = new Array(3);
sub.fill(-1);

var a = [];
a[0] = sub;
a[1] = sub;
a[2] = sub;

a[0][1] = 0;

console.log(sub); // changed too

Because here is what array.fill is doing:

var a = new Array(10);
a.fill(Math.random()); 

console.log(a);   // not 10 different random numbers, but the same random number is assigned to the whole array

Second question

It has nothing to do with arrays. It's a comma operator like the one used in the for loops (for example), to group expressions into one and returning the value of the last:

console.log((1, 2)); // 2
console.log((1, 5, "last")); // last
console.log((1, 5, 5 * 11 + 10)); // 65

// the parens are used to distinguish the comma operator from the parameter separator

So a[1, 2] is the same as a[2] because the value of 1, 2 is 2!

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

1 Comment

@JohnLittle I added some explanation for your second question too! Just saw it! You're welcome!
1

You are filling the array with same reference new Array(3).fill(-1) in all three rows and therefore any change to one will be reflected everywhere.

Try:

var a = new Array(n);
for (var i = 0; i < n; i++) {
  a[i] = new Array(n);
}
//where n = 3 for your case.

Comments

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.