0

Hello I am learning javascript programming and I am doing an algorithm exercice where you basicly have to convert the split letters into digits.

I have a **split **variable that I use to update part of my code.

I want this variable to remain constant so I didn't put any line in my code to change it value.

Nevertheless, when I console.log the split variable value his value is updating. Why is that ?

d = {
  "ZERO": 0,
  "ONE": 1,
  "TWO": 2,
  "THREE": 3,
  "FOUR": 4,
  "FIVE": 5,
  "SIX": 6,
  "SEVEN": 7,
  "EIGHT": 8,
  "NINE": 9
}


let result = []
let split = [ [], [], [], [], [], [], [], [], [], [] ]
let array = [ [], [], [], [], [], [], [], [], [], [] ]

for (var w = 0; w <= 9; w++) {
  array[w] = [Object.keys(d)[w].split('')]
  split[w] = [Object.keys(d)[w].split('')]
}

function digitsRecovery(s) {
  for (var i = 0; i < s.length; i++) {
    console.log(split)

    for (var j = 0; j < array.length; j++) {
      array[j].push([j])
      
      for (var t = 0; t < array[j].length; t++) {
        if (array[j][t].includes(s[i])) {
          array[j][t] = array[j][t].filter(x => x != s[i])
        }

        if (array[j][t].length === 0) {
          console.log(j, array[j][t].length)
          result.push(j)

          array[j][t] = split[j][0]
        }
      }

      if (split[j][0].includes(s[i])) {
        array[j].push(split[j][0])
      } else {
        array[j] = split[j]
      }
    }
  }
}


digitsRecovery("ONETWOTHREE")
  • `array[j] = split[j]` will not clone the value but assign *the same array* which is on `split[j]` to `array[j]`. Therefore, mutating `array[j]` from that point forward, changes the one and only array which is also reachable through `split[j]` – VLAZ Mar 23 '22 at 11:55

0 Answers0