Largest no. in Array using Recursion

Shubham Tiwari - Aug 3 '22 - - Dev Community

Hello guys today i want to show you how to find largest number in array using recursion.
Well i found this question today and then searched the stackoverflow😂 and found this solution and then tried to understand this solution.
Lets get started...

Code -

const findMax = arr => {
  if (!Array.isArray(arr)) throw 'Not an array'
  if (arr.length === 0) return undefined
  const [head, ...tail] = arr
  if (arr.length === 1) return head
  return head > findMax(tail) 
    ? head
    : findMax(tail)
}

console.log(findMax([1,9,10,28,78,10]))
Enter fullscreen mode Exit fullscreen mode

Working -

  • First we will check that the argument passed is an arrow or not , if it is not an array then throw an error
  • Then we will check if the length of array is 0 , if it is , return undefined.
  • In the next line , we destructured the array in two parts - head and tail, head containes the first element of the array and ...tail contains the rest of the array
  • After that we check that if the array length is 1 , if it is then we will return the head (the first and only element of that array)
  • Then we used the ternary operator to provide the condition, if the head is greater than findMax(tail) meaning the head element is the first element and findMax(tail) will give the first element from the tail array which is the next element jsut after that , so we will compare those two , if the condition is true , we will return the head element as the largest and if the condition is false then we will recursively check the tail and use the first element of that array as head and the rest as other tail element
  • So, Recursively it will check and compare all the elements in the array and gives us the largest one.

It looks quite confusing and i tried my best to explain and if you find any point wrong please correct it in the comment section.

Easy and Fast approach

const findMax = array => Math.max(...array);
Enter fullscreen mode Exit fullscreen mode

THANK YOU FOR CHECKING THIS POST
^^You can help me by some donation at the link below Thank you👇👇 ^^
☕ --> https://www.buymeacoffee.com/waaduheck <--

Also check these posts as well
https://dev.to/shubhamtiwari909/javascript-map-with-filter-2jgo

https://dev.to/shubhamtiwari909/e-quotes-3bng

https://dev.to/shubhamtiwari909/deploy-react-app-on-netlify-kl

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
Terabox Video Player