Search code examples
julia

How do you select a subset of an array based on a condition in Julia


How do you do simply select a subset of an array based on a condition? I know Julia doesn't use vectorization, but there must be a simple way of doing the following without an ugly looking multi-line for loop

julia> map([1,2,3,4]) do x
       return (x%2==0)?x:nothing
       end
4-element Array{Any,1}:
  nothing
 2
  nothing
 4

Desired output:

[2, 4]

Observed output:

[nothing, 2, nothing, 4]

Solution

  • You are looking for filter. Here is an example an filter(x->x%2==0,[1,2,3,5]) returning [2].