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

In Python,

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

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

In Python,

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

1 Like

```
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> ? 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> 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
```

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.

In the mean time:

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

3 Likes