2

I would like to create a 2d array, but i found an interesting behavior

const column = 10;
const row = 10;

let matrix = new Array(row).fill(new Array(column).fill(0));

matrix[0][1] = 1;

console.log(matrix)

and to my surprise i get the result as below:

0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 
0 2 0 0 0 0 0 0 0 0 

the entire column number 1 is set to 1, may I know why am I getting this behavior?

thefourtheye
  • 233,700
  • 52
  • 457
  • 497
Tim
  • 3,755
  • 3
  • 36
  • 57
  • 1
    all array elements are referring to a single array – Pranav C Balan Aug 04 '16 at 07:25
  • @PranavCBalan do u mind explain more? – Tim Aug 04 '16 at 07:28
  • `new Array(column).fill(0)` creates an array with length `column` and elements as `0`. `new Array(row).fill(....)` which fills with the array you were created, which is not creating different array for each... instead the reference to the array act as element – Pranav C Balan Aug 04 '16 at 07:33

2 Answers2

2

The Array#fill method filling with the same array that the elements are the reference to a single array. So you need to create separate arrays as elements. So updating one will reflect all other since they are not different array they are the same.

Using Array.from() you can create and generate values by map function.

const column = 10;
const row = 10;

let matrix = Array.from({
  // create array of length `row`
  length: row 
  // map function to generate values
}, () => new Array(column).fill(0));

matrix[0][1] = 1;

console.log(matrix)
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • sry, still dont get it..why is it reference to a single array? since it generates `row` times of that new array? – Tim Aug 04 '16 at 07:39
  • 1
    @Tim : first it creates an array of length `row` afterward it filling with a single array..... the fill act like `matrix[0] = matrix[1] = .. = matrix[row - 1] = new Array(column).fill(0);` so all the array elemnts are refering to same array.... – Pranav C Balan Aug 04 '16 at 07:42
  • 1
    @Tim : The array would be like `ref=[.....];[ref,ref,ref,...,ref]` .... – Pranav C Balan Aug 04 '16 at 07:45
1

@PranavCBalan have right.

It's something like that:

let matrix = new Array(row);
var x = new Array(column).fill(0);
matrix[0] = matrix[1] = .. = matrix[column - 1] = x;

Your matrix is array of the one object.

ventaquil
  • 2,780
  • 3
  • 23
  • 48