Remove a value from a Kotlin array
This article explores different ways to remove a value from an array in Kotlin.
Since the size of an array cannot be changed in Kotlin, we cannot remove a value from it. However, we can create a new array, and then copy all the values from the original array into the new array, except the one which we want to remove. There are several ways to do that:
1. Using filter() function
The idea is to filter the array to remove the specified value and accumulate the remaining elements into the new array using the toIntArray() function. This removes all occurences of a value from the array.
|
1 2 3 4 5 6 7 8 9 10 |
fun removeItem(array: IntArray, value: Int): IntArray { return array.filter { it != value }.toIntArray() } fun main() { var array: IntArray = intArrayOf(8, 2, 1, 10, 4, 8, 9) val value = 4 array = removeItem(array, value) println(array.contentToString()) } |
Output:
[8, 2, 1, 10, 8, 9]
For typed arrays, you can use the toTypedArray() function:
|
1 2 3 4 5 6 7 8 9 10 11 |
inline fun <reified T> removeItem(array: Array<T>, value: T): Array<T> { return array.filter { it != value }.toTypedArray() } fun main() { var array = arrayOf<String?>("B", "A", "B", "D", "A") val value = "B" array = removeItem(array, value) println(array.contentToString()) } |
Output:
[A, D, A]
2. Using System.arraycopy() function
If you want to remove a value by its index, consider using the System.arraycopy() function for better performance. The idea is to allocate a new array of size one less than the original array. Then call the System.arraycopy() function to copy the values before and after that index into the new array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun removeItem(array: Array<String?>, index: Int): Array<String?> { val result = arrayOfNulls<String>(array.lastIndex) System.arraycopy(array, 0, result, 0, index) if (array.size != index) { System.arraycopy(array, index + 1, result, index, array.lastIndex - index) } return result } fun main() { var array = arrayOf<String?>("A", "C", "B", "C", "D") val index = 1 array = removeItem(array, index) println(array.contentToString()) } |
Output:
[A, B, C, D]
That’s all about removing a value 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 :)