DEV Community

mrmatteorusso
mrmatteorusso

Posted on Edited on

Get the Largest Number

For any given array of arrays of numbers, create largerNumber function that sums up the content of each sub-array(where possible) and return the larger number.

Here examples of arrays and their results:


largesetNumber([[1, 2], [2, 10], [3, 4]]); //12
largesetNumber([[1, 2, 100,1], [2, 10], [3, 4]]); //104
largesetNumber([[1], [2, 10], [3, 4]]);//12
largesetNumber([[], [2, 10], [3, 4]]);//12
largesetNumber([]);//'empty array'
Enter fullscreen mode Exit fullscreen mode

Assumptions

  • items are all numbers or empty arrays

Knowledge

  • how to access a nested array
  • how to sum-up its nested items

Pseudo-code

  1. mapping through each nested array
  2. sum up each value inside their nested array
  3. choose the largest number

Solution

const largesetNumber = (array) => {
    if(array.length<1){
        return "empty array";
    }
    return Math.max(...array.map(item => item.length? item.reduce((acc, curr) => acc + curr) : 0))
}
Enter fullscreen mode Exit fullscreen mode

Comment(s) (random)

  • originally I did not think about a statement to "filter out empty arrays" not empty nested arrays: an if statement and a ternary operator made the job
  • initially while the map was looping through the nested loop I would push the result of reduce inside another array, but a more efficient way was found
// const largerNumber = (array) => {
//     if(array.length<1){
//         return "this is an empty array";
//     }

//     const result = [];
//     array.forEach((item, index) => item.length>0 ? result.push(item.reduce((acc, curr)=> acc + curr)): console.log(`Array at position ${index} is empty`))
//     return Math.max(...result)

// }
Enter fullscreen mode Exit fullscreen mode
  • Math.max does not take an array. It takes a set of parameters. The spread operator provides all of the values of the array as individual parameters.

Top comments (0)