Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting the indexes of duplicate elements in arrays (Ruby)

I have an array in Ruby that has some duplicate elements. E.g.:

fruits = ["apples", "bananas", "apples", "grapes", "apples"]

When I do the following:

fruits.index("apples")
# returns 0

I only get the first occurrence of "apples" which is, in this case, fruits[0]. Is there a way that I can run something similar to the above code and get the indexes of the other occurrences of "apples"? If I can't run something similar to the above code, how else can I get the indexes of the duplicate elements?

like image 538
GDP2 Avatar asked Apr 14 '15 20:04

GDP2


People also ask

How to check for duplicates in Ruby array objects?

Ruby Array objects have another method, count. In this case, you are interested in duplicates (objects which appear more than once in the array). The appropriate test is a.count (obj) > 1.

How to remove duplicate elements from an array in JavaScript?

Use the uniq method to remove duplicate elements from arrays with minimal code. Remove duplicates. In an array, any element value may occur. But often we want just unique, non-duplicate elements. We invoke the uniq method to correct this problem. Array Uniq and "uniq!" remove all except the first element with a value.

How do I compare two arrays in Ruby?

If you are comparing two different arrays (instead of one against itself) a very fast way is to use the intersect operator & provided by Ruby's Array class. # Given a = ['a', 'b', 'c', 'd'] b = ['e', 'f', 'c', 'd'] # Then this... a & b # => ['c', 'd']

How do I UNIQ an array with duplicated numbers?

The array has two duplicated numbers: a 2 and a 3. We invoke the "uniq!" method, which operates in-place. So: When we call "uniq!" we do not assign another array to it. The methods imply changes the "values" array, which we reuse. Next: We create an array of strings. This one has three string values equalling "dog."


2 Answers

Taking a page from procedural languages, we could write:

fruits.each_index.select { |i| fruits[i]=="apples" }
  #=> [0, 2, 4]
like image 122
Cary Swoveland Avatar answered Nov 15 '22 12:11

Cary Swoveland


You can do this:

fruits.to_enum.with_index.select{|e, _| e == "apples"}.map(&:last)
# => [0, 2, 4]
like image 27
sawa Avatar answered Nov 15 '22 10:11

sawa