Skip to content

Instantly share code, notes, and snippets.

@janosh
Created October 18, 2020 06:45
Show Gist options
  • Save janosh/099bd8061f15e3fbfcc19be0e6b670b9 to your computer and use it in GitHub Desktop.
Save janosh/099bd8061f15e3fbfcc19be0e6b670b9 to your computer and use it in GitHub Desktop.
argMin and argMax functions for JavaScript
const argFact = (compareFn) => (array) => array.map((el, idx) => [el, idx]).reduce(compareFn)[1]
const argMax = argFact((min, el) => (el[0] > min[0] ? el : min))
const argMin = argFact((max, el) => (el[0] < max[0] ? el : max))
argMin([42, -5, 3.14, 1e6]) // 1
argMax([42, -5, 3.14, 1e6]) // 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment