# Minimum by key function

**URL:** https://discourse.julialang.org/t/minimum-by-key-function/56056
**Category:** New to Julia
**Tags:** question
**Created:** [February 25, 2021, 11:15pm UTC](https://discourse.julialang.org/t/minimum-by-key-function/56056 "2021-02-25T23:15:03Z")
**Posts on this page:** 3
**Page:** 1

<div class="post-metadata">

### Author: ![jzr](https://avatars.discourse-cdn.com/v4/letter/j/eb9ed0/32.png) [@jzr](https://discourse.julialang.org/u/jzr)
#### Post date: [February 25, 2021, 11:15pm UTC](https://discourse.julialang.org/t/minimum-by-key-function/56056/1 "2021-02-25T23:15:03Z")

</div>

How can I find the minimum value of an array, but evaluating the minimum through a key function?

In Python,

```julia
In [6]: min([-3, -1, 2], key=abs)
Out[6]: -1

```

---

<div class="post-metadata">

### Author: ![lmiq](https://sea2.discourse-cdn.com/julialang/user_avatar/discourse.julialang.org/lmiq/32/18314_2.png) [@lmiq](https://discourse.julialang.org/u/lmiq)
#### Post date: [February 25, 2021, 11:24pm UTC](https://discourse.julialang.org/t/minimum-by-key-function/56056/2 "2021-02-25T23:24:18Z")

</div>

```julia
julia> minimum(abs,[-2,1,3])
1

```

By the way, I found out this by using the “help” of the REPL, which is very useful:

```julia
julia> ? minimum

```

Uhm, I note that it is not the same! Sorry. I will keep searching ☹

edit: at least in Julia you can write your own function if searching takes longer than that:

```julia
julia> function minbykey(x;by=identity)
         min = by(x[firstindex(x)])
         imin = 1
         for i in firstindex(x)+1:lastindex(x)
           y = by(x[i])
           if y < min
             min = y
             imin = i
           end
         end
         x[imin]
       end
minbykey (generic function with 2 methods)

julia> minbykey([-2,-1,3],by=abs)
-1

```

---

<div class="post-metadata">

### Author: ![contradict](https://avatars.discourse-cdn.com/v4/letter/c/ac91a4/32.png) [@contradict](https://discourse.julialang.org/u/contradict)
#### Post date: [February 25, 2021, 11:50pm UTC](https://discourse.julialang.org/t/minimum-by-key-function/56056/3 "2021-02-25T23:50:38Z")

</div>

As far as I know there is no built-in way right now, but 2-arg versions of `findmin` and `argmin` are [coming in 1.7](https://github.com/JuliaLang/julia/pull/35316).

In the mean time:

```julia
minimumby(f, iter) = reduce(iter) do x, y
    f(x) < f(y) ? x : y
end

```
