skip to Main Content

I have a for loop like below

let oArr = [1,1,1,1,1,1,1,1,1]
let n = 9
let k = 5
let mArr = [] 
for (let j = 0; j < k; j++) {
  for (let i = 0; i < n; i++) {
    if (i === 0) {
      mArr[i] = oArr[0] + oArr[1]
    } else if (i === (n - 1)) {
      mArr[i] = oArr[i] + oArr[i - 1]
    } else {
      mArr[i] = oArr[i] + oArr[i + 1] + oArr[i - 1]
    }
  }
  console.log(`j == ${j},mArr == ${mArr}`)
  oArr = mArr
}

so it should be

mArr[1] = oArr[1] + oArr[2] + oArr[0]

since oArr = mArr is outside the for(i) loop

but the output I get is like below

mArr[1] = oArr[1]*2 + oArr[2] + oArr[0]

Please tell me what went wrong?
is there a misplacement of

oArr = mArr

2

Answers


  1. you should change your code as below:

    let oArr = aRandomArray;
    let n = 100;
    let k = 5;
    
    for (let j = 0; j < k; j++) {
        let mArr = []; // First create a new array for each iteration of the outer loop
        
        for (let i = 0; i < n; i++) {
            if (i === 0) {
                mArr[i] = oArr[0] + oArr[1];
            } else if (i === (n - 1)) {
                mArr[i] = oArr[i] + oArr[i - 1];
            } else {
                mArr[i] = oArr[i] + oArr[i + 1] + oArr[i - 1];
            }
        }
        
        oArr = mArr; // Last update oArr after the inner loop has completed
    }
    

    creating a new mArr array within each iteration of the outer loop, you ensure that the calculations are performed on the original oArr values without any interference from previous iterations.

    Then, after the inner loop is completed, you update oArr with the newly calculated values stored in mArr, I hope it helps.

    Login or Signup to reply.
  2. When you do

    oArr = mArr
    

    You are not copying the arrays, but in fact both are pointing to the very same array. So when you then do

    mArr[0] = oArr[0] + oArr[1]
    

    in the next iteration of the outer loop, you are not only modifying the first element of mArr but also of oArr. Same for all other assignments. Use

    oArr = mArr.slice()
    

    to create a copy of your array instead of both pointing to the same array.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search