DEV Community

Cover image for Easiest way return largest numbers in arrays - Daily JavaScript #6
Dhairya Shah
Dhairya Shah

Posted on • Originally published at codewithsnowbit.hashnode.dev

Easiest way return largest numbers in arrays - Daily JavaScript #6

Hello πŸ‘‹,
It is very easy to do πŸ™‚

function largestNumber(arr) {
    // You can do this!
    const largest = [];
    for (let i = 0; i < arr.length; i++) {
        largest.push(Math.max(...arr[i]));
    }
    return largest;
  }

  console.log(largestNumber([[105, 35, 63, 89], [130, 270, 128, 216], [312, 335, 357, 399], [1000, 1001, 857, 1]]))
Enter fullscreen mode Exit fullscreen mode

This was a quick article, I hope it helped you


Thank you for reading, have a nice day!

Discussion (2)

Collapse
jonrandy profile image
Jon Randy • Edited on

A less verbose way would be:

const largestNumbers = arrs => arrs.map(arr => Math.max(...arr))
Enter fullscreen mode Exit fullscreen mode
Collapse
lukeshiru profile image
Luke Shiru

You could split this into two different functions, making it easier to read, and more reusable:

const largestNumber = array => Math.max(...array);
const largestNumbers = arrays => arrays.map(largestNumber);
Enter fullscreen mode Exit fullscreen mode

This way you can get the largest number in an array, and the largest numbers in an array of arrays :D

Cheers!