Daniel
Daniel

Reputation: 51

how to reset value in a 2D array in javascript

I am really confused about this 2D array.

For example:

let arr = Array(2)
arr.fill(Array(2))

arr[0][0]=1

And the result of arr is [1,empty][1,empty]

Why is it like that? I just want the first item in the first array to be set as 1

Upvotes: 1

Views: 188

Answers (3)

Ilijanovic
Ilijanovic

Reputation: 14904

The docu says...

Value to fill the array with. (Note all elements in the array will be this exact value.)

That means they share the same adress in memory.

You need a different approach to fill your array..

let arr = Array.from({length: 2}, e => Array(2))

arr[0][0]=1

console.log(arr);

Upvotes: 0

Yash Shah
Yash Shah

Reputation: 1654

Array(2) is the empty array that is copied to each element of arr.

But all the copies of Array(2) are the deep-copies.

So, changes in one of the deep-copy will be reflected in all the copies of Array(2).

let arr = Array(2)
arr.fill(Array(2))

arr[0][0]= 1
// [ [ 1, <1 empty item> ], [ 1, <1 empty item> ] ]

arr[0][1] = 2
// [ [ 1, 2 ], [ 1, 2 ] ]

Upvotes: 1

useryg
useryg

Reputation: 134

Because you use 1 instance of an array to fill you first array (arr). So arr[0] and arr[1] are actually the same instance, they point to the same address. If you want to fill you array arr with new arrays, loop over you first array arr, and then assign them new array.

const arr = Array(2);

for (let i = 0; i < arr.length; i++) {
    arr[i] = Array(2);
}

arr[0][0] = 1;

Upvotes: 3

Related Questions