Find the Largest Integer
Today we are going to be looking at another code challenge solution. We will be looking at HackerRanks findLargestInteger challenge, and walk through the solution step by step together.
Our Challenge:
We need to create a function that takes in an array of any integers. Inside that function we need to determine the largest integer in that array and return it.
Step 1: We need to define a function. As always you can use an arrow function if you want too. But for now we are going to be using a function declaration.
let array = [0,34,89,200,11,-34]
function findLargestInteger(array){
}
Above I went ahead and defined an array of integers using the let keyword. Just for teaching purposes so that you can see the information that we are dealing with. Then we defined our function findLargestInteger that takes in the array that we defined.
Step2: Now that we know what the data is and what it looks like we need a way to iterate over it in our function.
let array = [0,34,89,200,11,-34]function findLargestInteger(array){ array.reduce((a,b) => )}
Here we will be using the reduce function. I think it's the most efficient way to compare two integers inside an array. For our purposes we need to find the biggest or largest integer.
Step 3: What do we use to find the biggest integer?
let array = [0,34,89,200,11,-34]function findLargestInteger(array){array.reduce((a,b) => Math.max(a,b), 0)}
For our purposes we are going to be utilizing the Math built in methods to find the biggest or largest integer. Here we are using the max function. For us it will determine what the largest integer is. If a is 0 in the array and b is 34 at the first iteration, b would then become the largest integer. But on the second turn of the iteration a is now 34 and b is now 89. It will do this until it has figured out which is the largest integer.
Step 4: Finally we need a way to return this integer once we find it.
let array = [0,34,89,200,11,-34]function findLargestInteger(array){let largeNum = array.reduce((a,b) => Math.max(a,b), 0);return largeNum;}
By setting our reduce method on our array to a variable we now have the power to save it in memory and then return it when the reduce method has evaluated all of the integers in the array.
And that's it! We now successfully have a way to find the largest number in any given array. I hope this has been insightful and helpful for you. Happy coding!