Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

199
Views
Is there a reason why multiple array elements are changing simultaneously after updating just one?

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' ]
]
about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!