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

135
Views
Change two-dimentional array's certain index value javascript

I'm trying to put certain value in certain two dimensional array but it appends different.

Here is my code.

const arr = []
const tdArr = []

arr.length = 5
arr.fill('p', 0)

for(let i = 0; i < arr.length; i++){
  tdArr.push(arr)
}

const makeRnd = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min)) + min
}

let firstRnd = makeRnd(0, 4)
let secRnd = makeRnd(0, 4)
let tdArr2 = [...tdArr]
tdArr2[firstRnd][secRnd] = 'q'

console.log(tdArr2)

I don't know why not (for example) tdArr2[0][1] is not changed but also change all second value of arrays.

It seems easy one but cannot google it :( Thanks for help!

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

0

Use tdArr.push([...arr]) in the for loop instead of tdArr.push(arr).

const arr = []
const tdArr = []

arr.length = 5
arr.fill('p', 0)

for(let i = 0; i < arr.length; i++){
  tdArr.push([...arr])
}

const makeRnd = (min, max) => {
  min = Math.ceil(min)
  max = Math.floor(max)
  return Math.floor(Math.random() * (max - min)) + min
}

let firstRnd = makeRnd(0, 4)
let secRnd = makeRnd(0, 4)
let tdArr2 = [...tdArr]
tdArr2[firstRnd][secRnd] = 'q'

console.log(tdArr2)

about 4 years ago · Juan Pablo Isaza Report

0

As mentioned by @Dave Newton every element of tdArr array is the same one which is a reference to arr so when you change a value of arr all elements of tdArr are changes as they all reference the same array.

I would push an array literal instead of creating an array and then push it or create a copy like mentioned in the answer above and push the copy on each iteration.

tdArr.push(['p']);
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!