aelor
aelor

Reputation: 11116

Sort array in Ruby on Rails

arr = [
  [0, "Moving Companies", 10],
  [0, "ab-thera-sensa", 5],
  [0, "belt-center", 16],
  [0, "isabel", 3],
  [0, "kreatio", 2],
  [0, "service1", 7],
  [0, "sorbion-sachet-multi-star", 6],
  [0, "sss", 15],
  [0, "telecom-service-industry", 14],
  [1, " AbsoPad", 13],
  [1, "telecom-service", 8],
  [2, "cutisorb-ultra", 12],
  [2, "sorbion-contact", 11],
  [2, "sorbion-sachet-multi-star", 9]
]

Suppose this is my array, now I want to sort it on the basis of the first element in descending order. I can do a arr.sort.reverse but the problem starts now

I get the array as :

[
    [2, "sorbion-sachet-multi-star", 9],
    [2, "sorbion-contact", 11],
    [2, "cutisorb-ultra", 12],
    [1, "telecom-service", 8],
    [1, " AbsoPad", 13],
    [0, "telecom-service-industry", 14],
    [0, "sss", 15], [0, "sorbion-sachet-multi-star", 6],
    [0, "service1", 7],
    [0, "kreatio", 2],
    [0, "isabel", 3],
    [0, "belt-center", 16],
    [0, "ab-thera-sensa", 5],
    [0, "Moving Companies", 10]
]

Now the array should be sorted on the basis of the second element in ascending order.

How can that be achieved?

The result should look like :

[
  [2, "cutisorb-ultra", 12],
  [2, "sorbion-contact", 11],
  [2, "sorbion-sachet-multi-star", 9],
  [1,.......]
]

Upvotes: 0

Views: 257

Answers (3)

bluexuemei
bluexuemei

Reputation: 419

please try:

arr.sort_by{|x|[-x[0],-x[2]]}

Upvotes: -1

Abdo
Abdo

Reputation: 14051

How about this?

arr.sort { |i,j| [j[0],j[2]] <=> [i[0],i[2]]  }

Outputs:

=> [[2, "cutisorb-ultra", 12],
 [2, "sorbion-contact", 11],
 [2, "sorbion-sachet-multi-star", 9],
 [1, " AbsoPad", 13],
 [1, "telecom-service", 8],
 [0, "belt-center", 16],
 [0, "sss", 15],
 [0, "telecom-service-industry", 14],
 [0, "Moving Companies", 10],
 [0, "service1", 7],
 [0, "sorbion-sachet-multi-star", 6],
 [0, "ab-thera-sensa", 5],
 [0, "isabel", 3],
 [0, "kreatio", 2]]

Upvotes: 0

R&#244;mulo Ceccon
R&#244;mulo Ceccon

Reputation: 10347

Customize the sorting with a block. First do a descending sort by the first element (0). If they are equal do instead an ascending sort by the second element (1):

arr.sort! do |a, b|
  result = b[0] <=> a[0]
  result = a[1] <=> b[1] if result == 0
  result
end

Upvotes: 2

Related Questions