Largest Numbers in Arrays - not working

Tell us what’s happening:

why its not working ??

Your code so far


function largestOfFour(arr) {
  // You can do this!
  let arrList = [];
  arr.forEach(row => { arrList.push(row.sort((a,b)=>a-b).slice(-1))});
  console.log(arrList);
  return arrList;
}

largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]);

Your browser information:

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

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

Hello @PrvnToddy,

Slice returns an array instead of number. In your case, it is array with 1 element. You can change your sorting function to: (a,b)=>b-a and then take the first element of the sorted array instead of the last one.

1 Like

Hi
you can also replace .slice(-1) by .pop() and there is no need to curly brackets in the arrow function.

1 Like

Thanks @sherbakov1
arr.forEach(row => { arrList.push(row.sort((a,b)=>b-a)[0])});

Yes, that usage works fine :blush:

1 Like