Finding a greatest number in a nested array in JavaScript


We have to write a simple function in JavaScript that takes in an array of Numbers (nested to any level) and return the greatest number present in the array.

For example − If the input array is −

const arr = [
   34, 65, 67,
   [
      43, 76, 87, 23, 56, 7,
      [
         54, 7, 87, 23, 79, 314, 2
      ],
      54
   ], 54, 4, 2
];

Then the output should be −

314

We will use recursion to find the greatest number in the array. Let’s write the code for it

Example

const arr = [
   34, 65, 67,
   [
      43, 76, 87, 23, 56, 7,
      [
      54, 7, 87, 23, 79, 314, 2
      ],
      54
   ], 54, 4, 2
];
const findGreatest = (arr, greatest = -Infinity) => {
   for(let i = 0; i < arr.length; i++){
      if(Array.isArray(arr[i])){
         return findGreatest(arr[i], greatest);
      };
      if(arr[i] > greatest){
         greatest = arr[i];
      }
   };
   return greatest;
};
console.log(findGreatest(arr));

Output

The output in the console will be −

314

Updated on: 26-Aug-2020

130 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements