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

Hello I am writing a code to find the max value in an array of sub arrays and am required to add that max value to a new array. My code is above. The problem is my code is pushing every value greater than the max to the new array. When I just want the true max without using the Math.max function. I believe this is happening because I do not have a way of updating the max when a new max is found. Some guidance would be very helpful

medOnline5
  • 73
  • 1
  • 5

3 Answers3

4

Initialize max in the outer loop (i) with -Infinity (the smallest "number" available"), then compare and update it in the inner loop, but only push it after the inner loop is done:

function largestOfFour(arr) {
  const newArr = [];
  for (let i = 0; i < arr.length; i++) {
    let max = -Infinity;
    for (let j = 0; j < arr[i].length; j++) {
      if (arr[i][j] > max) {
        max = arr[i][j];
      }
    }

    newArr.push(max);
  }
  return newArr;
}

const result = largestOfFour([[4, 3, 2, 1], [1, 2, 3, 4], [500, 600, 400], [300, 1000, 700]]);

console.log(result);
Ori Drori
  • 183,571
  • 29
  • 224
  • 209
2

You could save the first value as start value for max and iterate from the second index.

Later push the max value of the nested array to the result array.

function largestOfFour(arrays) {
    const maxValues = [];
    for (let [max, ...array] of arrays) {
        for (const value of array) if (max < value) max = value;
        maxValues.push(max);
    }
    return maxValues;
}

console.log(largestOfFour([[3, 2, 1, 7], [2, 6, 4, 9], [2, 2, 1, 1], [4, 3, 6, 7]]));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

From your description of the problem i can understand that you want the maximum value from the subarrays of the array. In this situation you do not need to use newArr.push(max) Inside the IF block. You can use this line after the two nested loop are finished. Then you use newArr.push(max); And then return newarr.

Aurora
  • 133
  • 11