Remove all occurrences of an element from an array in Kotlin
This article explores different ways to remove all occurrences of a given element from an array in Kotlin.
Since arrays are fixed-sized in Kotlin, you can’t remove an element from it. However, you can create a copy of the original array, which excludes the specified element. We can do this in several ways:
1. Using filter() function
The trick is to filter all occurrences of the given element using the filter() function and return the list as an array using the toTypedArray() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 |
fun remove(arr: Array<Int>, target: Int): Array<Int> { return arr.filter { key: Int -> key != target } .toTypedArray() } fun main() { var arr: Array<Int> = arrayOf(1, 3, 1, 2, 4, 2, 5) val target = 2 arr = remove(arr, target) println(arr.contentToString()) // [1, 3, 1, 4, 5] } |
2. Using MutableList
The idea is to iterate over the array and insert each element that doesn’t match the specified element in a new MutableList instance. Finally, return the list as an array using toTypedArray() function.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
fun remove(arr: Array<Int>, target: Int): Array<Int> { val result: MutableList<Int> = ArrayList() for (key in arr) { if (key != target) { result.add(key) } } return result.toTypedArray() } fun main() { var arr: Array<Int> = arrayOf(1, 3, 1, 2, 4, 2, 5) val target = 2 arr = remove(arr, target) println(arr.contentToString()) // [1, 3, 1, 4, 5] } |
Another plausible way is to insert all array elements into a MutableList and then use the removeAll() function to remove all occurrences of the given key from the list.
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
fun remove(arr: Array<Int>, target: Int): Array<Int> { val result = arr.toMutableList() result.removeAll(listOf(target)) return result.toTypedArray() } fun main() { var arr: Array<Int> = arrayOf(1, 3, 1, 2, 4, 2, 5) val target = 2 arr = remove(arr, target) println(arr.contentToString()) // [1, 3, 1, 4, 5] } |
That’s all about removing all occurrences of the specified 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 :)