0

Hi Community I struggle to understand the following behavior. Its a typicall Monday problem. All I want is to fill the empty array slots with the integer 0.

myArray = [
  [1, ,1, ],
  [ , ,1, ],
  [ , ,1, ],
  [1, , , ],
]
      
for (var a = 0; a < myArray.length; a++) {
  for (var b = 0; b < myArray[a].length; b++) {
    if (myArray[a][b] == undefined) {
        myArray[a][b] = 0
    }
  }
  console.log("myArray[" + a + "]["+ b +"]" + " = " + myArray[a][b])
}

3 Answers 3

2

You are trying to access b outside the loop

Just move it to the loop

myArray = [
  [1, , 1, ],
  [, , 1, ],
  [, , 1, ],
  [1, , , ],
]

for (var a = 0; a < myArray.length; a++) {
  for (var b = 0; b < myArray[a].length; b++) {
    if (myArray[a][b] == undefined) {
      myArray[a][b] = 0
    }
    console.log("myArray[" + a + "][" + b + "]" + " = " + myArray[a][b])
  }
}

Also, better never use var:

myArray = [
  [1, , 1, ],
  [, , 1, ],
  [, , 1, ],
  [1, , , ],
]

for (let a = 0; a < myArray.length; a++) {
  for (let b = 0; b < myArray[a].length; b++) {
    if (myArray[a][b] == undefined) {
      myArray[a][b] = 0
    }
  }
  console.log("myArray[" + a + "][" + b + "]" + " = " + myArray[a][b])
}

If you would use let you will get an error without debugging

Sign up to request clarification or add additional context in comments.

Comments

0

Another way to fill-in empty values with zerro

const myArray = [
  [1, ,1, ],
  [ , ,1, ],
  [ , ,1, ],
  [1, , , ],
];

const filled = myArray.map(level1 => [...level1].map(value => value ? value : 0));

console.log(filled);
.as-console-wrapper { max-height: 100% !important; top: 0 }

Comments

0

The OP code was logging values within the outer loop which is out of scope of b which was defined within the inner loop. Log properties right after they are defined which in your case should be the inner loop.

const arrArrs = [
  [ 1, '',  1, '' ],
  [ '', '', 1, '' ],
  [ '', '', 1, '' ],
  [ 1, '', '', '' ]
];

for (let a = 0; a < arrArrs.length; a++) {
  for (let b = 0; b < arrArrs[a].length; b++) {
    if (arrArrs[a][b] != '') {
      console.log(`arrArrs[${a}][${b}] = ${arrArrs[a][b]}`);
      continue;
    }
    arrArrs[a][b] = 0;
    console.log(`arrArrs[${a}][${b}] = ${arrArrs[a][b]}`);
  }
}
console.log(JSON.stringify(arrArrs));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.