Remove first item from a Kotlin array
This article explores different ways to remove the first item from an array in Kotlin.
There is no standard solution to remove items from the fixed-length arrays in Kotlin. However, we can create a new array containing all items from the original array except the first. There are several ways to achieve that in Kotlin:
1. Using copyOfRange() function
A common and concise solution to remove the first item from an array is using the copyOfRange() function. It can easily copy the desired range of elements from the original array into a new array.
|
1 2 3 4 5 6 7 8 9 |
fun removeFirstItem(array: IntArray): IntArray { return array.copyOfRange(1, array.size) } fun main() { var array: IntArray = intArrayOf(2, 3, 4, 8, 7, 1) array = removeFirstItem(array) println(array.contentToString()) } |
Output:
[3, 4, 8, 7, 1]
2. Using Range
Another option is to generate a range of indices between 1 and lastIndex (both inclusive), transform the indices into their corresponding elements with 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 removeFirstItem(array: IntArray): IntArray { return (1.. array.lastIndex) .map { array[it] } .toIntArray() } fun main() { var array: IntArray = intArrayOf(2, 3, 4, 8, 7, 1) array = removeFirstItem(array) println(array.contentToString()) } |
Output:
[3, 4, 8, 7, 1]
3. Using System.arraycopy() function
Finally, we can allocate a new array of one less size than the original array and then call the System.arraycopy() function to copy the specified range from source to destination array.
|
1 2 3 4 5 6 7 8 9 10 11 |
fun removeFirstItem(array: IntArray): IntArray { val result = IntArray(array.lastIndex) System.arraycopy(array, 1, result, 0, array.lastIndex) return result } fun main() { var array: IntArray = intArrayOf(2, 3, 4, 8, 7, 1) array = removeFirstItem(array) println(array.contentToString()) } |
Output:
[3, 4, 8, 7, 1]
That’s all about removing the first 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 :)