kotlin

Remove an item from Array in Kotlin

In this post, we are going to explain different methods that can be used to delete elements from an array using Kotlin. We will be converting the array to a mutable list to delete items from array.

fun removeElement(arr: Array<String>, itemIndex: Int): Array<String> {
    val arrList = arr.toMutableList()
    
    arrList.removeAt(itemIndex)
    
    return arrList.toTypedArray()
}

fun main() {
	var fruits = arrayOf<String>("Apple", "Banana", "Orange", "Papaya")
    
    // Remove second element from array
    fruits = removeElement(fruits, 2)
    
    println(fruits.contentToString())
}

Output

[Apple, Banana, Papaya]

We have created an array called fruits that contain multiple items. We want to delete an item that has an index 2. To remove the item we have created a function named 'removeElement'. In this function, we are taking two parameters. First is the array from where you want to delete the item. The second is the index of the item that needs to be removed. 

We are converting the array to a mutable list using the .toMutableList() function and using removeAt() function of the mutable list, we are removing the item.

Remove an item from Mutable List in Kotlin

If we have a mutable list then we can easily remove the item from it. The mutable list has a function removeAt() that takes the index as a parameter and removes that item from the Mutable List.

Syntax

MutableList.removeAt(index)

Code example

fun main() {
    val mList = mutableListOf<Int>(10, 20, 30, 40, 50, 60)
    
    mList.removeAt(3)
    
    println(mList)
}

Output

[10, 20, 30, 50, 60]
Was this helpful?