Search code examples
arraysstringjuliaflatten

Julia: Flattening array of `String`s


This is essentially the same question as Julia: Flattening array of array/tuples but for array of Strings. The Iterators.flatten(xs) solution shown in the above thread is excellent for numbers. But, with Strings, Iterators.flatten() flattens a String into characters!

julia> f(xs...) = collect(Iterators.flatten(xs))
f (generic function with 1 method)

julia> f("oh", ["a", "b"], "uh")
6-element Vector{Any}:
 'o': ASCII/Unicode U+006F (category Ll: Letter, lowercase)
 'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)
 "a"
 "b"
 'u': ASCII/Unicode U+0075 (category Ll: Letter, lowercase)
 'h': ASCII/Unicode U+0068 (category Ll: Letter, lowercase)

How do you get an Array of Strings

"oh"
"a"
"b"
"uh"

from the above call to f()?

It would be nice if you can tell the iterator to regard String as scalar.


Solution

  • Not really sure if there is a built-in function that can do that, but it's not that hard to write it yourself. Maybe something like this:

    function custom_flatten(xs...)
        result = String[]
        for x in xs
            if isa(x, AbstractArray) || isa(x, Tuple)
                append!(result, custom_flatten(x...))
            else
                push!(result, x)
            end
        end
        return result
    end
    
    xs = ["hello", ["a", "b"], "world", [["nested"], "array"]]
    flattened = custom_flatten(xs...)
    println(flattened)  
    # Output: Any["hello", "a", "b", "world", "nested", "array"]
    

    You may as well add check if element is string and throw error or something since you asked for array of strings.