filter(function, collection)

Return a copy of collection, removing elements for which function is false. For associative collections, the function is passed two arguments (key and value).


julia> filter((x) -> x % 3 == 0, [1:10])        # divisible by 3
3-element Array{Int64,1}:
julia> array = Int[1,2,3]
       filter(x -> x % 2 == 0, array)
1-element Array{Int64,1}:
julia> array = Int[1,2,3]
       filter(x -> x==3, array) 
1-element Array{Int64,1}:
  1. Filter elements from an array using a function:

    julia> arr = [1, 2, 3, 4, 5];
    julia> filter(x -> x > 2, arr)
    3-element Array{Int64,1}:

    This example filters out elements from the array arr using the given function x -> x > 2, which keeps only the elements greater than 2.

  2. Filter elements from a dictionary based on a condition:

    julia> dict = Dict("apple" => 10, "banana" => 20, "orange" => 15);
    julia> filter((k, v) -> v > 15, dict)
    Dict{String,Int64} with 1 entry:
     "banana" => 20

    Here, the filter function is applied to the dictionary dict using the function (k, v) -> v > 15, which keeps only key-value pairs where the value is greater than 15.

  3. Filter strings from an array based on a condition:
    julia> words = ["apple", "banana", "orange", "grape"];
    julia> filter(s -> length(s) > 5, words)
    2-element Array{String,1}:

    This example filters out strings from the array words using the condition length(s) > 5, which keeps only the strings with a length greater than 5.

Common mistake example:

julia> arr = [1, 2, 3, 4, 5];
julia> filter(x -> x < 0, arr)

In this example, the provided filter function x -> x < 0 returns false for all elements in the array arr. As a result, the filtered array becomes empty. It's important to ensure that the filter function returns the desired condition for the elements in the collection to avoid such mistakes.

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.

*Required Field

Checking you are not a robot: