0

While attempting to make a change to a single array element by adding a string to it, it then updates the rest of the array elements with the same string value. Instead of changing a single element, it has updated the rest of the array with the same value.

I have tried to find an explanation of why more than one array element is changing without a loop, but it does not look possible without .apply, ..., or a loop:

let arrayFiller = Array(20).fill([]);
let myArray= ['foo', 'foo', 'foo'];
[].push.apply(myArray, arrayFiller);
console.log(myArray);
myArray[3][0] = 'bar';
console.log(myArray);
// Outputs: [
  'foo',     'foo',     'foo',
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ]
]

What I expected:

let arrayFiller = Array(20).fill([]);
let myArray= ['foo', 'foo', 'foo'];
[].push.apply(myArray, arrayFiller);
console.log(myArray);
myArray[3][0] = 'bar';
console.log(myArray);
// Outputs: [
  'foo',     'foo',     'foo',
  [ 'bar' ], [], [],
  [], [], [],
  [], [], [],
  [], [], [],
  [], [], [],
  [], [], [],
  [], []
]

Btw, this also works:

let arrayFiller = Array(20).fill([]);
let myArray= ['foo', 'foo', 'foo'];
[].push.apply(myArray, arrayFiller);
console.log(myArray);
myArray[4][0] = 'bar'; // Changed from myArray[3][0] to myArray[4][0]
console.log(myArray);
// Outputs: [
  'foo',     'foo',     'foo',
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ], [ 'bar' ],
  [ 'bar' ], [ 'bar' ]
]
Gamewire
  • 1
  • 2
  • Consider: `.fill([])` is like doing `const subarr = []; ....fill(subarr);` Further changes change the *single* `subarr` - there's only one. Use `Array.from` instead – CertainPerformance Apr 24 '22 at 23:06

0 Answers0