filter

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).

Examples

julia> filter((x) -> x % 3 == 0, [1:10])        # divisible by 3
3-element Array{Int64,1}:
 3
 6
 9
julia> array = Int[1,2,3]
       filter(x -> x % 2 == 0, array)
1-element Array{Int64,1}:
 2
julia> array = Int[1,2,3]
       filter(x -> x==3, array) 
1-element Array{Int64,1}:
 3
  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}:
    3
    4
    5

    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}:
    "banana"
    "orange"

    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)
Int64[]

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
Details

Checking you are not a robot: