Skip to main content

How to remove elements at specific indices from an array in Kotlin

How to remove elements at specific indices from an array in Kotlin.

Here's a step-by-step tutorial on how to remove elements at specific indices from an array in Kotlin:

  1. Initialize an array: Start by creating an array in Kotlin. You can declare an array and assign values to it using the following syntax:
val array = arrayOf(1, 2, 3, 4, 5)

In this example, we have created an array with five elements.

  1. Create a mutable list: In Kotlin, arrays have a fixed size, so to remove elements from specific indices, we need to convert the array into a mutable list. To do this, use the toMutableList() function:
val mutableList = array.toMutableList()

Now, the mutableList variable holds a mutable list with the same elements as the array.

  1. Remove elements at specific indices: To remove elements at specific indices, use the removeAt() function of the mutable list. Pass the index of the element you want to remove as an argument to this function. For example, to remove the element at index 2, use the following code:
mutableList.removeAt(2)

After executing this line, the element at index 2 (value 3 in this case) will be removed from the mutableList.

  1. Convert the mutable list back to an array: If you need the final result to be an array, you can convert the mutable list back to an array using the toTypedArray() function:
val newArray = mutableList.toTypedArray()

Now, the newArray variable holds the modified array with the element at the specified index removed.

Here's the complete code example:

val array = arrayOf(1, 2, 3, 4, 5)
val mutableList = array.toMutableList()
mutableList.removeAt(2)
val newArray = mutableList.toTypedArray()

In this example, the element with the value 3 is removed from the array.

Note that this approach modifies the original array by converting it to a mutable list. If you want to keep the original array unchanged, make a copy of the array before converting it to a mutable list.

You can also remove multiple elements at once by passing multiple index arguments to the removeAt() function. For example:

mutableList.removeAt(1)
mutableList.removeAt(3)

This will remove elements at index 1 and 3 from the mutable list.

That's it! You now know how to remove elements at specific indices from an array in Kotlin.