2

Given any 2D array, e.g,

val in = Array( Array(59, 45, 32), 
                Array(20, 88, 5), 
                Array(49, 72, 89))

would like to sort it by the third column, so that

val out = Array( Array(20, 88, 5),
                 Array(59, 45, 32),                       
                 Array(49, 72, 89))

Many Thanks.

3 Answers 3

7

This should work, but will fail if your arrays are of size less than 3:

scala> in.sortBy(_(2))

Output:

res0: Array[Array[Int]] = Array(Array(20, 88, 5), Array(59, 45, 32), Array(49, 72, 89))

You may also make this fail-safe like this:

in.sortBy {
  case arr @ Array(_) if arr.size >= 3 => arr(2)
  case arr => Int.MaxValue // or any other value. Using MaxValue will make the invalid arrays be last ones
}
Sign up to request clarification or add additional context in comments.

2 Comments

Your second solution can write as scala> in.sortBy { case Array(_, _, x, _*) => x; case _ => Int.MaxValue }
Thanks. I think there are several ways to do the same thing and I just picked the first one I came to :)
1
in.sortWith(_(2) < _(2))

will sort the array, using the third element of the Array.

Comments

1

If your array is Array[Array[Int]], you just need to use yourArray.sortBy(_(3)). 3 is your field index, which you want to order according to this column.

But, if your array is not Array[Array[Int]], you can't use sortBy directly. You'd better to use Sorting which is imported from scala.util.Sorting

Here is my code.

import scala.util.Sorting

Sorting.quickSort(yourArray)(new Ordering[Array[String]] {
  def compare(x: Array[String], y: Array[String]) = {
    x(3) compare y(3)
  }
})

My array is Array[Array[String]], x(3) is one field which you want to compare. Of course, if you want to reverse sorting, you just need to use y(3) compare x(3) to replace x(3) compare y(3).

If your array is other type, you just need to use your type to replace Array[String]

Comments

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.