Remove last item from a Kotlin array
This article explores different ways to remove the last item from an array in Kotlin.
Arrays in Kotlin hold a fixed number of values of a single type. The fixed length of the array is decided upon its creation, which remains fixed post creation. So, there is no standard way to remove values from it. However, we can create a new array containing all values from the original array except the last. There are several plausible ways to do that in Kotlin:
1. Using copyOf() function
The standard solution to remove the last item from an array is using the copyOf() function, which can copy desired elements of the original array into a new array starting from the beginning.
|
1 2 3 4 5 6 7 8 9 |
fun removeLastItem(array: IntArray): IntArray { return array.copyOf(array.lastIndex) } fun main() { var array: IntArray = intArrayOf(5, 3, 4, 7, 6, 8) array = removeLastItem(array) println(array.contentToString()) } |
Output:
[5, 3, 4, 7, 6]
Similar to the copyOf() function, we have the copyOfRange() function, which can accept a range of elements to copy to the new array.
|
1 2 3 4 5 6 7 8 9 |
fun removeLastItem(array: IntArray): IntArray { return array.copyOfRange(0, array.lastIndex) } fun main() { var array: IntArray = intArrayOf(5, 3, 4, 7, 6, 8) array = removeLastItem(array) println(array.contentToString()) } |
Output:
[5, 3, 4, 7, 6]
2. Using System.arraycopy() function
Another option is to leverage the System.arraycopy() function, which can copy the specified range from the source array to the destination array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeLastItem(array: IntArray): IntArray { val result = IntArray(array.lastIndex) System.arraycopy(array, 0, result, 0, array.lastIndex) return result } fun main() { var array: IntArray = intArrayOf(5, 3, 4, 7, 6, 8) array = removeLastItem(array) println(array.contentToString()) } |
Output:
[5, 3, 4, 7, 6]
3. Using Range
Alternately, we can generate a sequentially ordered range between 0 (inclusive) and lastIndex (exclusive), transform each index to the corresponding element in the original array using the map() function, and return an array of Int containing all the mapped elements.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeLastItem(array: IntArray): IntArray { return (0 until array.lastIndex) .map { array[it] } .toIntArray() } fun main() { var array: IntArray = intArrayOf(5, 3, 4, 7, 6, 8) array = removeLastItem(array) println(array.contentToString()) } |
Output:
[5, 3, 4, 7, 6]
That’s all about removing the last item from an array in Kotlin.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)