filter!
filter!(function, collection)
Update collection
, removing elements for which function
is false
. For associative collections, the function is passed two arguments (key and value).
Examples
julia> foo = [1:5];
julia> function isOdd(x)
x % 2 != 0
end
julia> filter!(isOdd, foo);
julia> foo
3-element Array{Int64,1}:
1
3
5
-
Filter even numbers from an array:
julia> arr = [1, 2, 3, 4, 5, 6]; julia> filter!(x -> x % 2 == 0, arr) 3-element Array{Int64,1}: 2 4 6
This example filters out the odd numbers from the array
arr
using the provided function. -
Filter strings containing specific characters:
julia> words = ["apple", "banana", "orange", "grape"]; julia> filter!(x -> contains(x, 'a'), words) 2-element Array{String,1}: "apple" "banana"
It filters the strings from the vector
words
that contain the character 'a' using the given function. - Filter key-value pairs in a dictionary:
julia> dict = Dict("apple" => 3, "banana" => 2, "orange" => 5, "grape" => 4); julia> filter!((k, v) -> v > 3, dict) Dict{String,Int64} with 2 entries: "orange" => 5 "grape" => 4
This example filters the key-value pairs from the dictionary
dict
based on the condition that the value is greater than 3.
Common mistake example:
julia> arr = [1, 2, 3, 4, 5];
julia> filter!(x -> x > 5, arr)
ERROR: MethodError: no method matching isless(::Int64, ::Nothing)
In this example, the provided function tries to compare the elements with 5, but there is no comparison defined between Int64
and Nothing
. Make sure the function used in filter!
is valid for the elements in the collection to avoid such errors.
See Also
append!, delete!, deleteat!, empty!, endof, filter, filter!, gc, get!, getkey, haskey, insert!, isempty, keys, map, map!, merge, merge!, pop!, prepend!, push!, reduce, resize!, shift!, splice!, unshift!, values,User Contributed Notes
Add a Note
The format of note supported is markdown, use triple backtick to start and end a code block.