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.
Add a comment
|
5 Answers
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]
2 Comments
Cary Swoveland
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?Lukas Baliak
@CarySwoveland I modify usage of map in this case. You have right, i use it "uncorrect" in this case.
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
Cyriac Domini Thundathil
Thank you for this. I got a shortened version of this which worked perfectly!
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
Santhosh
This wont get you the output as per your requirements. Luka's or Rick's answers are what you might be looking for.
Vrushali Pawar
Have you checked array b...? I forgot to paste that output.. check once by your own