Kotlin – Delete element at specific index in Array

Delete element at specific index in Array in Kotlin

To delete element at specific index in an Array in Kotlin, we can use array slicing technique.

arr.sliceArray(0 until index) + arr.sliceArray(index + 1 until arr.size)

In the above expression, there are two parts. The first part slices the Array from starting to the element just before the specified index. The second part slices the Array from the index after the specified index to the last of the Array.

A simple example with an input and desired output is

Input Array
["apple", "banana", "cherry", "mango"]

Remove element at index = 2

Output Array
["apple", "banana", "mango"]

Examples

Remove element at index=2 in given Array

In the following program, we take an Array of strings in arr, delete the element at index=2 in the Array, and print the resulting Array to output.

Kotlin Program

fun main(args: Array<String>) {
    val arr = arrayOf<String>("apple", "banana", "cherry", "mango")
    val index = 2
    val resultArray = arr.sliceArray(0 until index) + arr.sliceArray(index + 1 until arr.size)
    println(resultArray.contentToString())
}

Output

[apple, banana, mango]