Selecting entries of an array based on selection criteria provided by other array

The most compact way to do this is probably

a[b .∈ (selection,)] # or a[b .∈ Ref(selection)]

but you have to use (type \in[tab] in REPL to get this symbol) in order to broadcast. The (,)or Ref means broadcast will treat selection as a scalar for broadcast.

This is not ideal for allocation/speed, in part because it creates an intermediate bit array. The fastest/least allocating solution I could come up with is not particularly pretty:

function myfun(a, b, selection)
    
    l = 0
    for bi ∈ b 
       if bi ∈ selection; l += 1; end
    end
    out = zeros(eltype(a), l)
    
    k = 1
    for i ∈ eachindex(a, b)
        if b[i] ∈ selection
            out[k] = a[i]
            k += 1
        end
    end
    
    return out
end
3 Likes