Skip to content

Instantly share code, notes, and snippets.

@stevengoldberg
Last active August 29, 2015 14:27
Show Gist options
  • Save stevengoldberg/88878443bc9cc3862b8d to your computer and use it in GitHub Desktop.
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
/**
* 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