Sort an Array based on the content of another Array in Kotlin
This is a situation where we have two Arrays, and we would like to sort the contents of the first array based on the values of the second array.
For example, say that we have an array of fruit names, and an array of their respective available stocks. We would like to sort the fruit names based on their available stocks.
Given arrays
------------
array1 [apple, banana, cherry, mango, fig]
array2 [5, 2, 8, 3, 1]
apple -> 5
banana -> 2
cherry -> 8
mango -> 3
fig -> 1
After rearrangement / sorting
-----------------------------
array1 [fig, banana, mango, apple, cherry]
array2 [1, 2, 3, 5, 8]
fig -> 1
banana -> 2
mango -> 3
apple -> 5
cherry -> 8
And let us see how to do that.
To sort an Array based on another Array in Kotlin,
Step 1 : Sort the indices of the second Array, based on the values.
val sortedIndicesArray2 = array2.indices.sortedBy { array2[it] }
Now, we have the order of indices in which we have to arrange the first array.
Step 2 : Create array from the indices returned in the above step, and the elements from the first Array.
val sortedArray1 = sortedIndicesArray2.map { array1[it] }.toTypedArray()
sortedArray1
has elements of first Array which are arranged in the ascending order of the elements from second Array.
Examples
Sort the Array fruitNames based on the Array stocks
In the following program, we take two Arrays: array1
and array2
. The Arrays are named this way to easily understand the example. The array1
consists of fruit names, and the array2
consists of the respective available stocks. And we are going to rearrange the elements of array1
such that they are ordered in ascending order of their respective available stocks.
Kotlin Program
fun main(args: Array<String>) {
val array1 = arrayOf("apple", "banana", "cherry", "mango", "fig")
val array2 = arrayOf(5, 2, 8, 3, 1)
val sortedIndicesArray2 = array2.indices.sortedBy { array2[it] }
val sortedArray1 = sortedIndicesArray2.map { array1[it] }.toTypedArray()
println(sortedArray1.contentToString())
}
Output
[fig, banana, mango, apple, cherry]
Explanation
Given arrays
------------
array1 [apple, banana, cherry, mango, fig]
array2 [5, 2, 8, 3, 1]
apple -> 5
banana -> 2
cherry -> 8
mango -> 3
fig -> 1
After rearrangement / sorting
-----------------------------
array1 [fig, banana, mango, apple, cherry]
array2 [1, 2, 3, 5, 8]
fig -> 1
banana -> 2
mango -> 3
apple -> 5
cherry -> 8