DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

Return Largest Numbers in Arrays (freecodecamp notes)

In this question we are asked to Return Largest Numbers in Arrays.

Tests that we should pass

largestOfFour([[4, 5, 1, 3], [13, 27, 18, 26], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return an array.
largestOfFour([[13, 27, 18, 26], [4, 5, 1, 3], [32, 35, 37, 39], [1000, 1001, 857, 1]]) should return [27, 5, 39, 1001].
largestOfFour([[4, 9, 1, 3], [13, 35, 18, 26], [32, 35, 97, 39], [1000000, 1001, 857, 1]]) should return [9, 35, 97, 1000000].
largestOfFour([[17, 23, 25, 12], [25, 7, 34, 48], [4, -10, 18, 21], [-72, -3, -17, -10]]) should return [25, 48, 21, -3].
Enter fullscreen mode Exit fullscreen mode

First answer

function largestOfFour(arr) {

 let maxInSubArr=0
 let newArr=[]

 for(let i=0;i<arr.length;i++){
   for (let j=0;j<arr[i].length;j++){

       if(maxInSubArr<arr[i][j]){
         maxInSubArr=arr[i][j]

       }
   }
   newArr.push(maxInSubArr)
   maxInSubArr=0

 }

  return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Second answer

function largestOfFour(arr) {

 let newArr=[]

 for(let i=0;i<arr.length;i++){

  let maxInSubArr = arr[i][0];

   for (let j=0;j<arr[i].length;j++){

       if(maxInSubArr<arr[i][j]){
         maxInSubArr=arr[i][j]

       }
   }
   newArr.push(maxInSubArr)


 }

  return newArr;
}
Enter fullscreen mode Exit fullscreen mode

Correct Answer is Answer 2, reason being, in the first answer we do not handle negative numbers, we set it to zero initially then reset it to zero once its pushed to return array, however in the second solution we are setting it to the first item in subarray

Top comments (1)

Collapse
 
karladler profile image
Karl Adler

If you want to have a 1-liner using modern JS:

myArray.map(subArr => subArr.sort((a, b) => b - a).at(0));
Enter fullscreen mode Exit fullscreen mode

For super large arrays it's recommended to convert it in a Float typed array to speed up sorting by up to 5X times! see: stackoverflow.com/a/53355543/1059828