Last active
March 7, 2023 01:32
-
-
Save engelen/fbce4476c9e68c52ff7e5c2da5c24a28 to your computer and use it in GitHub Desktop.
Single-line ArgMax for JavaScript
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
/** | |
* Retrieve the array key corresponding to the largest element in the array. | |
* | |
* @param {Array.<number>} array Input array | |
* @return {number} Index of array element with largest value | |
*/ | |
function argMax(array) { | |
return array.map((x, i) => [x, i]).reduce((r, a) => (a[0] > r[0] ? a : r))[1]; | |
} | |
console.log(argMax([ 5.2, 1.4, 9.6, 1.8, 3.2, 2.4 ])); | |
// Output: 2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
With dictionnary-like object you can also do this :