Find the Largest Number in an Array
Write a function that finds the largest number in an array.
Advanced
Instructions
Write a function that receives an array of numbers and returns the largest number in it.
Tests
0/6
Function Call:
Expected:
findLargest([100,10,20])
100
Run test
findLargest([-5, -2, 0])
0
Run test
findLargest([-1])
-1
Run test
findLargest([-3,30,9,-9,0,0,0])
30
Run test
findLargest([])
"undefined"
Run test
Hidden Test
?
Run test
See Solution
Math library
const findLargest = (myArray) => {
if(myArray.length === 0) return undefined
return Math.max(...myArray)
}
Explanation
The Math.max() function is used to find the largest number in a list of numbers. The spread operator is used to pass the elements of the array as arguments to the Math.max() function.
Complexity Analysis
The time complexity for this solution is O(n) where n is the number of elements in the array.
For loop
For loop
const findLargest = (myArray) => {
if(myArray.length === 0) return undefined
let largest = myArray[0]
for(let i = 1; i < myArray.length; i++){
if(myArray[i] > largest){
largest = myArray[i]
}
}
return largest
}
Lodash
import {max} from lodash
const findLargest = (myArray) => {
return max(myArray)
}
Array sorting
const findLargest = (myArray) => {
return myArray.sort((a,b) => b - a)[0]
}
Any improvement idea? Share with us!