Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array.fill(Array) creates copies by references not by value [duplicate]

Tags:

I'm trying to create a 6 by 12 Matrix using Array.fill

let m = Array(6).fill(Array(12).fill(0)); 

While this works, the problem is that the inner Arrays are actually all referencing the same Array object.

let m = Array(6).fill(Array(12).fill(0)); m[0][0] = 1; console.log(m[1][0]); // Outputs 1 instead of 0 

I wanted (and expected) the value of m[1][0] to be 0.

How can I force Array.fill fill copy-by-values of the given argument (eg: Array(12).fill(0) is the argument in my case) instead of copying by reference ?

like image 611
XCS Avatar asked Jun 21 '16 16:06

XCS


People also ask

Which array prototype function returns a reference to a new array every time?

Definition and Usage. The every() method executes a function for each array element. The every() method returns true if the function returns true for all elements.

How do you duplicate an array in Javascript?

To duplicate an array, just return the element in your map call. numbers = [1, 2, 3]; numbersCopy = numbers. map((x) => x); If you'd like to be a bit more mathematical, (x) => x is called identity.


2 Answers

You could use Array.from() instead:

Thanks to Pranav C Balan in the comments for the suggestion on further improving this.

let m = Array.from({length: 6}, e => Array(12).fill(0));    m[0][0] = 1;  console.log(m[0][0]); // Expecting 1  console.log(m[0][1]); // Expecting 0  console.log(m[1][0]); // Expecting 0

Original Statement (Better optimized above):

let m = Array.from({length: 6}, e => Array.from({length: 12}, e => 0)); 
like image 103
KevBot Avatar answered Sep 18 '22 12:09

KevBot


You can't do it with .fill(), but you can use .map():

let m = new Array(6).map(function() { return new Array(12); }); 

edit oh wait that won't work; .map() won't iterate through the uninitialized elements. You could fill it first:

let m = new Array(6).fill(null).map(function() { return new Array(12); }); 
like image 21
Pointy Avatar answered Sep 18 '22 12:09

Pointy