Home > Back-end >  How do I sort a 2d array of ints in Kotlin using sortedBy?
How do I sort a 2d array of ints in Kotlin using sortedBy?

Time:11-25

new in Kotlin stuck on something basic.

I have this 2d array:

val intervals: Array<IntArray> = arrayOf(
    intArrayOf(1, 3),
    intArrayOf(15, 18),
    intArrayOf(8, 10),
    intArrayOf(2, 6),
)

by how do I sort this by the first element of each sub-array.

the output should be: (1,3); (2,6); (8,10); (15,18)

I tried this but I am not clear of the syntax and did not work.

intervals.sortedBy { it[0] }

thank you.

CodePudding user response:

That is exactly how you do that, the only thing you could change would maybe be to do it.first() instead of it[0], but that might just be preference. Of course, if you don't know the values of your array and it might have any internal array with 0 elements, then you should also check for that.

The reason I think you believe it is not working, is because you are expecting it to sort in place. There are 2 different methods you can use: sortBy {} and sortedBy{}. The first sorting the initial array, and the latter returning a new sorted list.

As for not understanding the syntax, I'd recommend reading the docs (that would have also shown the difference between the 2 functions). But to make it a bit more understandable, you could name the it param.

//this creates a new list
val newList = intervals.sortedBy { internalArray -> internalArray.first() }

or

//this sorts the given array
intervals.sortBy { internalArray -> internalArray.first() }
  • Related