Kotlin – Delete specific Element from Array

Delete specific Element from Array in Kotlin

To delete all the occurrences of a specific element from an Array in Kotlin, you can use Array.filter() function.

["apple", "banana", "cherry", "banana", "apple"]

remove "apple"

["banana", "cherry", "banana"]

Call the function filter() on the Array object and pass the condition that the current element does not match the specified element.

arr.filter { it != elementToDelete }

filter() function returns a List. You may convert the returned List to an Array using List.toTypedArray() function.

arr.filter { it != elementToDelete }.toTypedArray()

Examples

Delete “apple” from the Array

In the following program, we take an Array of strings in arr, and delete all the occurrences of element "apple" from the Array.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf<String>("apple", "banana", "cherry", "banana", "apple")
    val elementToDelete = "apple"
    val result = arr.filter { it != elementToDelete }.toTypedArray()
    println(result.contentToString())
}

Output

[banana, cherry, banana]