Last active
August 29, 2015 14:27
-
-
Save stevengoldberg/88878443bc9cc3862b8d to your computer and use it in GitHub Desktop.
An ES6 utility function for finding the nth-max value in an array
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
/** | |
* An ES6 utility function for finding the nth-max value in an array. | |
*/ | |
let nthMax = (array, nth = 1) => { | |
if(nth > (array.length - 1)) { | |
throw new Error('Nth max value exceeds array size'); | |
} | |
let newArr = array, | |
i = 0; | |
while(i < nth) { | |
array.splice(newArr.indexOf(Math.max(...newArr)), 1); | |
i++; | |
} | |
return Math.max(...newArr); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment