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?

3
  • 1
    all array elements are referring to a single array Commented Aug 4, 2016 at 7:25
  • @PranavCBalan do u mind explain more? Commented Aug 4, 2016 at 7: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 Commented Aug 4, 2016 at 7:33

2 Answers 2

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)

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

3 Comments

sry, still dont get it..why is it reference to a single array? since it generates row times of that new array?
@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....
@Tim : The array would be like ref=[.....];[ref,ref,ref,...,ref] ....
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.