Home > OS >  for loop auto increment variable javascript
for loop auto increment variable javascript

Time:08-05

I am trying to do an exercise in freecodecamp, where we have to search through an array and return the largest number inside the subarray, when i was trying to do it using the following code:

function largestOfFour(arr) {
  let newArr = []
  for(let i = 0 ; i< arr.length; i  ) {
    for(let j = 0; j< arr[i].length; j  ) {
      if(arr[i][j] > arr[i][j 1]) {
        newArr[i] = arr[i][j]
        console.log(i)
      }
    }
  }
  return arr;
}

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]);

here the when I console.log(i) it returns 0 1 3 3 never entering the 3rd loop where i=2. can someone please explain why is this happening?

CodePudding user response:

find the largest number, you should use Number.NEGATIVE_INFINITY as the initial values of newArr, and use newArr[i] as the compare value. so the code is like this:

function largestOfFour(arr) {
  let negaInf = Number.NEGATIVE_INFINITY; 
  let newArr = [negaInf, negaInf,negaInf, negaInf];
  for(let i = 0 ; i< arr.length; i  ) {
    for(let j = 0; j< arr[i].length; j  ) {
      if(arr[i][j] > newArr[i]) {
        newArr[i] = arr[i][j]
        console.log(i)
      }
    }
  }
  return newArr;
}

console.log(largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]));

the reason of that is in the third array, the value of numbers are increasing, when i = 2, j = 0, it compare 32(arr[2][0]) and 35(arr[2][1]), condition false, 35(arr[2][1]) and 37(arr[2][2]), condition false, 37(arr[2][2]) and 39(arr[2][3]), condition false, 39(arr[2][3]) and undefined(arr[2][4]) (Yes your code has a out of index access), condition false. so it had not change the value of newArr[2]

  • Related