0

I want to make an array out of sum of positive numbers in row, but my code counts negative elements if they're standing in first column. Can I get some help with this please?

My code:

<!DOCTYPE html>
<html>
<head>
    <title>Document</title>
</head>
<body>
    <div id="result-container"></div>
          <script>
          let myArray = [3]; 
        
              for (let i = 0; i < 3; i++) { 
                myArray[i] = [];  
                for (let j = 0; j < 3; j++) { 
                  myArray[i][j] = Math.floor(Math.random() * 20 - 10) + 1;  
                } 
        } 
          
        let output = myArray;

        
        console.log(myArray);
        let F = [];

              for (let i = 0; i < myArray[0].length; i++) {
                let posSum = myArray[i][0];
                for (let j = 1; j < myArray.length; j++) {
                  if (myArray[i][j] > 0) {
                    posSum += myArray[i][j];
                  }

                }
          F.push(posSum);
        }
        output += `Array F: ${F}`;
        console.log(F);
        document.getElementById('result-container').innerHTML = output;
          </script>
</body>
</html>

Example of problem: problem

MihaVar
  • 3
  • 2
  • Welcome to Stack Overflow! This is a good opportunity for you to start familiarizing yourself with [using a debugger](https://stackoverflow.com/q/25385173/328193). When you step through the code in a debugger, which operation first produces an unexpected result? What were the values used in that operation? What was the result? What result was expected? Why? To learn more about this community and how we can help you, please start with the [tour] and read [ask] and its linked resources. – David May 25 '23 at 12:02
  • What is the purpose of `let myArray = [3];`? – PeterKA May 25 '23 at 16:33

1 Answers1

0

The culprit is this line of code:

let maxElement = myArray[i][0];

Here you're intentionally setting your counter to the value of the first element inside the array. So if it's e.g. -1 you're starting to count from -1 and not zero.

Also the second for-loop increments from element 1 onwards - it should start at index 0.

let myArray = [3];

for (let i = 0; i < 3; i++) {
  myArray[i] = [];
  for (let j = 0; j < 3; j++) {
    myArray[i][j] = Math.floor(Math.random() * 20 - 10) + 1;
  }
}

let output = myArray;


console.log(myArray);
let F = [];

for (let i = 0; i < myArray[0].length; i++) {
  let maxElement = 0;
  for (let j = 0; j < myArray.length; j++) {
    if (myArray[i][j] > 0) {
      maxElement += myArray[i][j];
    }

  }
  F.push(maxElement);
}
console.log(F);
obscure
  • 11,916
  • 2
  • 17
  • 36