Return Largest Numbers in Arrays - problem

Tell us what’s happening:
I can’t figure out why my code is not correct. Everything works fine but still FCC don’t want it. Anyone can explain what am I doing bad?

Your code so far


function largestOfFour(arr) {
  // You can do this!
  let temp=0;
  let final_arr=0;
  let biggest=0;
  console.log(Date.now());
  console.log(arr);
  arr.filter(ele => {
    for(let i=0; i < ele.length; i++){
      //console.log(ele); 
      if(ele[i] >= biggest){
        biggest = ele[i];
        final_arr = temp;
      }
    }
    temp++;
  });
  console.log("arr[" + final_arr + "] = " + arr[final_arr]);
  return arr[final_arr];
}

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

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36.

Link to the challenge:
https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/basic-algorithm-scripting/return-largest-numbers-in-arrays/

If you console.log your function you’ll see that you’re returning the last sub-array.

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

You should return the largest element of each sub-array.

1 Like

OMG… Sorry, I didn’t understand that task… I fixed it the lazy and awful way but it works and I think this is the most important in this case :smile:

function largestOfFour(arr) {
  // You can do this!
  let largest_arr = [-100,-100,-100,-100];
  let temp = 0;
  arr.filter(ele => {
    for(let i = 0; i < ele.length; i++){
      if(ele[i] > largest_arr[temp]) largest_arr[temp] = ele[i];
    }
    temp++;
  });
  return largest_arr;
}

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