diff --git a/base/array.jl b/base/array.jl index 310bc66dbff4e..c84fdc937bf2f 100644 --- a/base/array.jl +++ b/base/array.jl @@ -2162,35 +2162,38 @@ indmin(a) = findmin(a)[2] """ indexin(a, b) -Return a vector containing the highest index in `b` for -each value in `a` that is a member of `b` . The output -vector contains 0 wherever `a` is not a member of `b`. +Return an array containing the highest index in `b` for +each value in `a` that is a member of `b`. The output +array contains `nothing` wherever `a` is not a member of `b`. # Examples ```jldoctest -julia> a = ['a', 'b', 'c', 'b', 'd', 'a']; +julia> a = ['a', 'b', 'c', 'b', 'd', 'a'] -julia> b = ['a','b','c']; +julia> b = ['a', 'b', 'c'] -julia> indexin(a,b) -6-element Array{Int64,1}: +julia> indexin(a, b) +6-element Array{Union{Nothing, Int64},1}: 1 2 3 2 - 0 + nothing 1 -julia> indexin(b,a) -3-element Array{Int64,1}: +julia> indexin(b, a) +3-element Array{Union{Nothing, Int64},1}: 6 4 3 ``` """ -function indexin(a::AbstractArray, b::AbstractArray) - bdict = Dict(zip(b, 1:length(b))) - [get(bdict, i, 0) for i in a] +function indexin(a, b::AbstractArray) + indexes = keys(b) + bdict = Dict(zip(b, indexes)) + return Union{eltype(indexes), Nothing}[ + get(bdict, i, nothing) for i in a + ] end function _findin(a, b) diff --git a/test/arrayops.jl b/test/arrayops.jl index 1e42072c00d25..87e90247214be 100644 --- a/test/arrayops.jl +++ b/test/arrayops.jl @@ -1393,13 +1393,14 @@ function i7197() end @test i7197() == (2,2) -# PR #8622 and general indexin test -function pr8622() - x=[1,3,5,7] - y=[5,4,3] - return indexin(x,y) -end -@test pr8622() == [0,3,1,0] +# PR #8622 and general indexin tests +@test indexin([1,3,5,7], [5,4,3]) == [nothing,3,1,nothing] +@test indexin([1 3; 5 7], [5 4; 3 2]) == [nothing CartesianIndex(2, 1); CartesianIndex(1, 1) nothing] +@test indexin((2 * x + 1 for x in 0:3), [5,4,3,5,6]) == [nothing,3,4,nothing] +@test indexin(6, [1,3,6,6,2]) == fill(4, ()) +@test indexin([6], [1,3,6,6,2]) == [4] +@test indexin([3], 2:5) == [2] +@test indexin([3.0], 2:5) == [2] #6828 - size of specific dimensions let a = Array{Float64}(uninitialized, 10)