user1934428
user1934428

Reputation: 22225

Find indices of array elements that fulfill a condition

I have an array, and I need an array of subscripts of the original array's elements that satisfy a certain condition.

map doesn't do because it yields an array of the same size. select doesn't do because it yields references to the individual array elements, not their indices. I came up with the following solution:

my_array.map.with_index {|elem,i| cond(elem) ? i : nil}.compact

If the array is large and only a few elements fulfill the conditions, another possibility would be

index_array=[]
my_array.each_with_index {|elem,i| index_array << i if cond(elem)}

Both work, but isn't there a simpler way?

Upvotes: 0

Views: 79

Answers (3)

J&#246;rg W Mittag
J&#246;rg W Mittag

Reputation: 369428

Another possible alternative:

my_array.select.with_index {|elem, _| cond(elem) }.map(&:last)

Upvotes: 3

Andrey Deineko
Andrey Deineko

Reputation: 52357

Nope, there is nothing inbuilt or much simpler that what you already got.

Variation:

my_array.each_with_index.with_object([]) do |(elem, idx), indices|
  indices << idx if cond(elem)
end

Upvotes: 4

Santhosh
Santhosh

Reputation: 29094

You can use Array#each_index with select

arr = [1, 2, 3, 4]
arr.each_index.select {|i| arr[i].odd? }
# => [0, 2] 

Upvotes: 2

Related Questions