Skip to content

Instantly share code, notes, and snippets.

@LeanSeverino1022
Last active September 2, 2019 07:10
Show Gist options
  • Save LeanSeverino1022/3cd16843a4a0e9593efc9d8ad8215162 to your computer and use it in GitHub Desktop.
Save LeanSeverino1022/3cd16843a4a0e9593efc9d8ad8215162 to your computer and use it in GitHub Desktop.
Find largest number #vanillajs
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)
*/
//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