I
I
Ilnar252016-07-06 11:17:32
ruby
Ilnar25, 2016-07-06 11:17:32

How to sort descending the largest number of elements in an array?

It is necessary to sort the array in descending order by the largest number of occurrences of the same values, followed by the removal of duplicate elements.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Andrey Demidenko, 2016-07-06
@Ilnar25

array = %w[a b a b c d e g j a e c d k o k i l p a e c f d e a d e f s d v c ]
result = Hash[array.each_with_object(Hash.new(0)) {|e, h| h[e] += 1 }.sort_by {|k,v| -v}].keys

UPD:
Version #2
array = %w[a b a b c d e g j a e c d k o k i l p a e c f d e a d e f s d v c ]
array.sort_by {|v| -array.count(v)}.uniq

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question