0
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,.......]
]

3 Answers 3

2

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
Sign up to request clarification or add additional context in comments.

1 Comment

You are correct +1. The edit makes sense to me what OP is looking for.
0

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]]

Comments

-1

please try:

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

1 Comment

can you please explain this

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.