DEV Community

Naveen Dinushka
Naveen Dinushka

Posted on

2

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

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

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

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

AWS GenAI LIVE!

GenAI LIVE! is a dynamic live-streamed show exploring how AWS and our partners are helping organizations unlock real value with generative AI.

Tune in to the full event

DEV is partnering to bring live events to the community. Join us or dismiss this billboard if you're not interested. ❤️