0

Recently, I was trying to create three-level deep nested arrays. Crazy, I know, but it was the best solution to my problem I could think of. The arrays are created with the following code.

const lengths = [2, 3];

const arrays = lengths.map((v, i) => {
    return Array(lengths[i]).fill([]);
});

arrays[0][0].push(1);

console.log(arrays);
// Expected: [ [ [ 1 ], [] ], [ [], [], [] ] ]
// Actual: [ [ [ 1 ], [ 1 ] ], [ [], [], [] ] ]

As you can see, I only push to array[0][0]. Yet, both [0][0] and [0][1] get pushed to. What is going on here? Is it a bug, or a feature? Some kind of weird memory management?

If it helps, I am using Node.js. Thanks in advance.

Andrew Lemons
  • 192
  • 1
  • 1
  • 7

1 Answers1

0

You are filling the entire array with the same array reference. Instead, you could use the mapping callback of Array.from to rectify this issue by returning a different array each time.

const lengths = [2, 3];

const arrays = lengths.map((v, i) => {
    return Array.from({length: lengths[i]}, _=>[]);
});

arrays[0][0].push(1);

console.log(arrays);
.as-console-wrapper{top:0;max-height:100%!important}
Unmitigated
  • 76,500
  • 11
  • 62
  • 80