Remove an element from an array in Kotlin
This article explores different ways to remove an element from an array in Kotlin.
Arrays hold a fixed number of items of a single type. Since the length of the array is fixed, we cannot remove elements from it. However, we can create a new array without the element being removed.
1. Using filter() function
The idea is to filter the array to remove the required element and accumulate the remaining values into a new array. This is demonstrated below for an Int Array.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun removeTarget(array: IntArray, target: Int): IntArray { return array .filter { it != target } .toIntArray() } fun main() { var array: IntArray = intArrayOf(2, 5, 7, 3, 4, 8, 9) val target = 4 array = removeTarget(array, target) println(array.contentToString()) } |
Output:
[2, 5, 7, 3, 4, 8, 9]
2. Using System.arraycopy() function
To remove an element from the array using its index, the recommended approach is using the System.arraycopy() function. The idea is to allocate a new array of one less size than the original array, and copy all the elements from the original array into the new array before and after that index.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
fun removeByIndex(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", "E") val index = 1 array = removeByIndex(array, index) println(array.contentToString()) } |
Output:
[A, B, C, D, E]
That’s all about removing an element 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 :)