Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Modifying an element of array in array

I want to modify values of row 50, default of value is -1

let rowUp = table.pos[51]
for (let i in rowUp){
    process.stdout.write(rowUp[i].val+'')
}
process.stdout.write('\n')
let rowSet = table.pos[50]
for (let i in rowSet){
    rowSet[i].val = 0
    process.stdout.write(rowSet[i].val+'')
}
process.stdout.write('\n')
let rowDn = table.pos[49]
for (let i in rowDn){
    process.stdout.write(rowDn[i].val+'')
}

And the result is

-1-1-1-1-1-1-1-1-1-1

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

0000000000

0000000000

I want it to be

-1-1-1-1-1-1-1-1-1-1

0000000000

-1-1-1-1-1-1-1-1-1-1

EDIT

I saw my error here

const cellData = await new cellSchema()
for (let posZ = 0; posZ < 100; posZ++) {
    let row = []
    for (let posX = 0; posX < 100; posX++) {
        row[posX] = cellData
    }
    table.pos[posZ] = row
}

It needs to be

for (let posZ = 0; posZ < 100; posZ++) {
    let row = []
    for (let posX = 0; posX < 100; posX++){
        const cellData = await new cellSchema()
        row[posX] = cellData
    }
    table.pos[posZ] = row
}

>Solution :

I suspect the nodes inside your rows are all references to the same object. So when you change the val attribute for one of them, it changes for all of them.

To fix this the right way you need to make sure to create copies for each node when creating your table.

To fix this in a hacky way in the case of your code snippet, here is what you can do:

let rowUp = table.pos[51]
for (let i in rowUp){
    process.stdout.write(rowUp[i].val+'')
}
process.stdout.write('\n')
let rowSet = table.pos[50]
for (let i in rowSet){
    rowSet[i] = { …rowSet[i], val: 0 }
    process.stdout.write(rowSet[i].val+'')
}
process.stdout.write('\n')
let rowDn = table.pos[49]
for (let i in rowDn){
    process.stdout.write(rowDn[i].val+'')
}

This will create a copy when you need to stray off from the commonly referenced object in your table.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading