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

140
Views
Change value of element inside nested array, array created with Array().fill()

Consider the code below. I want to change only the second elements value in the second list in matrix. The problem is, that somehow all elements are changed. How can this be?

let matrix = Array(2).fill(Array(2).fill(0));
// [[0, 0], [0, 0]]
matrix[1][1] = 8
console.log(matrix)
// [[0, 8], [0, 8]]

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

This is because all elements inside matrix are pointing to or referencing the same list. By wanting to change one instance of the list, you change them all because you thereby change the list being pointed to. To avoid this, create an empty nested array using for-loops instead:

let matr = [];
for (let i = 0; i < 2; i++) {
  matr.push(Array(2).fill(0))
}
matr[1][1] = 8
console.log(matr)

about 4 years ago · Juan Pablo Isaza Report
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!