Skip to content Skip to sidebar Skip to footer

Javascript: Pushing In An Empty 3d Array

I create an empty 3x3x1 3D array [ [[],[],[]], [[],[],[]], [[],[],[]] ] Now, The element at position arr[1][1] is [], So, If I execute arr[1][1].push(1) it should insert 1 o

Solution 1:

Use one more nested map. I think that fill call will fill the first map with the same array in each of the 2nd dimension instead of a unique one which means the 2nd dimension all reference the same array.

The docs from fill even note that the value will be the exact same:

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

Also (array is an object):

If the first parameter is an object, each slot in the array will reference that object.

const arr1 = [...newArray(3)].map(e => [...newArray(3)].fill([]));
const arr2 = [[[],[],[]],[[],[],[]],[[],[],[]]];
const arr3 = [...newArray(3)].map(() => [...newArray(3)].map(() => []));

arr1[1][1].push(1);
arr2[1][1].push(1);
arr3[1][1].push(1);

console.log(JSON.stringify(arr1)); // [[[],[],[]],[[1],[1],[1]],[[],[],[]]]console.log(JSON.stringify(arr2)); // [[[],[],[]],[[],[1],[]],[[],[],[]]]console.log(JSON.stringify(arr3)); // [[[],[],[]],[[],[1],[]],[[],[],[]]]

In other words:

const expandedArr1 = [...newArray(3)].map(() => {
  /*
   * From MDN fill documentation:
   * Value to fill the array with. (Note all elements in the array will be this exact value.)
   */return [...newArray(3)].fill([]); // Every element will get this exact value (reference)
});

// They are the same reference:console.log(expandedArr1[1][1] === expandedArr1[1][2]);

Solution 2:

The reason this happens is because fill method fills the "exact value" in all the three.

MDN : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/fill See the Note in Parameter value description.

var arr1 = [...new Array(3)].map(e => [...new Array(3)].map(e=>[])); // Note that i have used a map with a functionreturninganarray([]) instead of your fill method
var arr2 = [[[],[],[]],[[],[],[]],[[],[],[]]];
arr1[1][1].push(1);
arr2[1][1].push(1);
console.log(arr1)
console.log(arr2)

Post a Comment for "Javascript: Pushing In An Empty 3d Array"