Last active
September 2, 2019 07:10
-
-
Save LeanSeverino1022/3cd16843a4a0e9593efc9d8ad8215162 to your computer and use it in GitHub Desktop.
Find largest number #vanillajs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var numbers = [4, 44, 21, 29, 12, 7]; | |
// Method 1: using Math.max | |
console.log( Math.max(...numbers) ); | |
//Method 2: using reduce | |
var max = numbers.reduce( | |
function(previousLargestNumber, currentLargestNumber) { | |
return (currentLargestNumber > previousLargestNumber) ? currentLargestNumber : previousLargestNumber; | |
} | |
); | |
console.log(max); | |
/* | |
If you can use method 1, then use it. | |
When we use the spread operator within Math.min / Math.max() it will expand, or spread out, our array and insert each variable as a separate parameter into Math.max()! | |
In other words: Math.max(...[1,2,3,4]) is the same as Math.max(1,2,3,4) | |
*/ |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//as a helper function | |
const arrMax = arr => Math.max(...arr); | |
// arrMax([20, 10, 5, 10]) -> 20 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment