Davi Barreira
Davi Barreira

Reputation: 1681

Julia - Multiple conditions for filtering array

Given an array like:

5-element Array{String,1}:
 "Computer science"
 "Artificial intelligence"
 "Machine learning"
 "Algorithm"
 "Mathematics"

How does one filter it by multiple conditions in Julia? For example, I want to obtain all the values that are not "Computer science" or "Artificial intelligence", hence, I want to obtain:

3-element Array{String,1}:
 "Machine learning"
 "Algorithm"
 "Mathematics"

Upvotes: 2

Views: 696

Answers (1)

Maybe something like this?

julia> x = ["Computer science", "Artificial intelligence", "Machine learning", "Algorithm", "Mathematics"]
5-element Array{String,1}:
 "Computer science"
 "Artificial intelligence"
 "Machine learning"
 "Algorithm"
 "Mathematics"

# Note the double parentheses, in order to build the
# ("Computer science", "Artificial intelligence") tuple
#
# It would also be possible (but probably less efficient) to put
# those values in a vector
julia> filter(!in(("Computer science", "Artificial intelligence")), x)
3-element Array{String,1}:
 "Machine learning"
 "Algorithm"
 "Mathematics"

Edit: as mentioned in comments, if the list of values to filter out is longer, it might be more efficient to build a Set instead of a Tuple:

julia> filter(!in(Set(("Computer science", "Artificial intelligence"))), x)
3-element Array{String,1}:
 "Machine learning"
 "Algorithm"
 "Mathematics"

Upvotes: 4

Related Questions