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]))
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);
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
Top comments (7)
It is not very helpful to check each call to see if arr is an array, if the array is empty, or if it only has one value.
Yeah for recursion approach it's not good
in this case for loop would be more appropriate...
Actually it is a question which is asked in an interview so i tried to solve it later because I was not able to solve it at the time of interview ๐๐
Okay, yeah, I would've refused that answer with "why on Earth would you do that?".
Yeah it won't make a difference Because they already rejected ๐๐
Yeah i should have mentioned this approach also ๐