Skip to content

Instantly share code, notes, and snippets.

@engelen
Last active March 7, 2023 01:32
Show Gist options
  • Save engelen/fbce4476c9e68c52ff7e5c2da5c24a28 to your computer and use it in GitHub Desktop.
Save engelen/fbce4476c9e68c52ff7e5c2da5c24a28 to your computer and use it in GitHub Desktop.
Single-line ArgMax for JavaScript
/**
* 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
@Gio-Mgm
Copy link

Gio-Mgm commented Aug 17, 2022

With dictionnary-like object you can also do this :

// with [0] at the end it return only the key, without it, it return [maxKey, maxValue]
const argMax = obj => Object.entries(obj).reduce((a, r) => a[1] > r[1] ? a : r)[0] 

// or if you need key value and index:
const argMax = obj => Object.entries(obj).map(([k, v], idx) => [k, v, idx]).reduce((a, r) => a[1] > r[1] ? a : r)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment