How can i separate between two arrays inside a parent array?

this code is a small example of what i want to do, i have this small example right here:

y=[[[1,0],[0,0],[1,1],[1,0],[1,0],[0,1]],[[1,0],[0,0],[1,1],[0,0]],[[1,0],[0,0],[1,1],[1,0],[1,0],[1,0]]]
array=[]
all_array=[]
for i in 1:length(y)
    for j in 1: length(y[i])
        if y[i][j]==[1,0]
            push!(array,y[i][j])
        end
        
    end
end

what i’m expecting when you return array is this :

[[[1,0],[1,0],[1,0]],[[1,0]],[[1,0],[1,0],[1,0],[1,0]]]

which is 3-element Array{Array{Array{Int64,1},1},1} but instead i get this:

8-element Array{Any,1}:
 [1, 0]
 [1, 0]
 [1, 0]
 [1, 0]
 [1, 0]
 [1, 0]
 [1, 0]
 [1, 0]

i don’t know what i’m missing here.

filter.(==([1,0]), y)

Should do what you want.


Edit
The reason your array is coming out “flat” is that you’re pushing all of the [1, 0] matches to the same array. If you wanted to write a function to do it yourself, think about writing it for each y[i] individually, and then calling that inner function in a loop over the arrays in y.

4 Likes

Or some array comprehension,

julia> [[x for x in yi if x==[1,0]] for yi in y]
3-element Array{Array{Array{Int64,1},1},1}:
 [[1, 0], [1, 0], [1, 0]]
 [[1, 0]]
 [[1, 0], [1, 0], [1, 0], [1, 0]]

which is the translation of the nested loops:

array = similar(y,0);
for i in y
    arri = similar(i,0)
    for j in i
        j == [1,0] && push!(arri,j)
    end
    push!(array,arri)
end
1 Like

the first method is brilliant and it’s working

indeed