How to filter map like array comprehension?

Viewed 130

With arrays, you can filter based on a condition:

[i for i=1:10 if isodd(i) ]

returns:

5-element Vector{Int64}:
 1
 3
 5
 7
 9

but attempting something similar with map results in nothing values:

julia> map(1:10) do i
           isodd(i) ? i : nothing
           end

reutrns:

10-element Vector{Union{Nothing, Int64}}:
 1
  nothing
 3
  nothing
 5
  nothing
 7
  nothing
 9
  nothing
1 Answers

map is a one-to-one mapping. So I'm afraid you can't do the same with map. Maybe what you are looking for is just filter?

julia> a = 1:10
1:10

julia> filter(isodd, a)
5-element Vector{Int64}:
 1
 3
 5
 7
 9
Related