Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Ruby – Identify and Update Duplicates in Array with Index Value

I have an array which may or may not include duplicates, but no nil or "" values.

array = ["Ballerina", "Lagoon", "Black", "Space", "Golden", "Lagoon"]

This is really the closest I’ve gotten to solving the problem, but the problem here is that I don’t know the duplicates, so its not really valid:

array.each_with_index.map {|value, index| array[index] == "Lagoon" ? index : ""}.uniq

What I’m looking to return is for any duplicates in the array to concatenate the index value onto the end of the array value. So the end result would be:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

array = ["Ballerina", "Lagoon 1", "Black", "Space", "Golden", "Lagoon 5"]

Thanks

>Solution :

One way is to use the Array count method inside your map loop.

array = ["Ballerina", "Lagoon", "Black", "Space", "Golden", "Lagoon"]


new_array = array.each_with_index.map do |value, index| 
    value_duplicated = array.count(value) > 1
    if value_duplicated 
        "#{value} #{index}"
    else
       value 
    end
end

puts new_array
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading