2

How can you find the indices of all elements in an array that has a particular value in ruby?
I.e. if you have an array [2,3,52,2,4,1,2], is there an easier way than to use loops, to get the indices of all 2 in the array? So the answer would be something like [0,3,6], if I am looking for 2.
The answer in Get index of array element faster than O(n) gives the solution if I want to find just one instance of the given element.

5 Answers 5

4

Maybe you can use this:

a = [2, 3, 52, 2, 4, 1, 2]

b = a.map.with_index{|k, i| i if k == 2}.compact
b
# => [0,3,6]

Or if you wanna to modify a variable so modify version.

a = [2, 3, 52, 2, 4, 1, 2]
a.map!.with_index{|k, i| i if k == 2}.compact!
a
# => [0,3,6]
Sign up to request clarification or add additional context in comments.

2 Comments

Since it is b you are building, why use map? You are mapping a to an array that you don't use. Isn't a.each_with_index more direct?
@CarySwoveland I modify usage of map in this case. You have right, i use it "uncorrect" in this case.
3

Try this one,

arr = [2,3,52,2,4,1,2]
    output = []
    arr.each_with_index do |v,i|
       if v == 2
         output << i
       end
    end

puts output #=> [0, 3, 6]

1 Comment

Thank you for this. I got a shortened version of this which worked perfectly!
2
a
# => [2, 3, 52, 2, 4, 1, 2]
b = []
# => []
a.each_with_index{|i, ind| b << ind if i == 2}
# => [2, 3, 52, 2, 4, 1, 2] 

2 Comments

This wont get you the output as per your requirements. Luka's or Rick's answers are what you might be looking for.
Have you checked array b...? I forgot to paste that output.. check once by your own
2
a = [2,3,52,2,4,1,2]

a.each_index.select { |i| a[i]== 2 }
  #=> [0, 3, 6] 

Comments

1
a.each_with_object([]).find_all {|i, index| i == 2}.map {|i, index| index }

I feel like there's still a shortcut though.

Another option might be :

a.each_with_object([]).with_index {|(i, result), index| result << index if i == 2 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.