mercredi 12 décembre 2018

Return largest number from nested arrays without math.max

I'm trying to return the largest number from each subarray to a new array. I feel like I'm really close, and I feel like if(temp[j] < x) {continue;} is out of place. What am I doing wrong? P.S. I know I can probably just use math.max() and save a lot of code, but i'm trying to get comfortable with for loops and arrays.

  function largestOfFour(arr) {
  let newArr = [];

  for(let i = 0; i < arr.length; i++) {
    let temp = arr[i];
    let counter = 0;
    for(let j = 0; j < temp.length; j++) {
      let x = 0;
      if(temp[j] > counter) {
      counter = temp[j];
      if(counter > x) {
        x = counter;
        if(temp[j] < x) {
          continue;
        }
      }
      newArr.push(temp[j]);

      }

    }
    console.log(arr[i])
  }
  console.log(newArr);
}

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

Aucun commentaire:

Enregistrer un commentaire