Skip to main content

How to remove specific elements from an array in Kotlin

How to remove specific elements from an array in Kotlin.

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

Step 1: Create an Array​

First, let's create an array with some elements. We'll use the arrayOf function to create a simple array of integers:

val numbers = arrayOf(1, 2, 3, 4, 5)

Step 2: Remove Element by Value​

To remove an element from the array by its value, we can use the filter function. This function takes a lambda expression as its argument, which determines the condition for filtering.

For example, let's remove the number 3 from the array:

val filteredArray = numbers.filter { it != 3 }

In this code, the lambda expression it != 3 checks if the current element of the array is not equal to 3. If the condition is true, the element is included in the filteredArray.

Step 3: Remove Element by Index​

To remove an element from the array by its index, we can use the filterIndexed function. This function also takes a lambda expression as its argument, but it provides the index as well as the element in the lambda expression.

For example, let's remove the element at index 2 from the array:

val filteredArray = numbers.filterIndexed { index, _ -> index != 2 }

In this code, the lambda expression index != 2 checks if the current index is not equal to 2. If the condition is true, the corresponding element is included in the filteredArray.

Step 4: Remove Multiple Elements​

To remove multiple elements from the array, we can combine the conditions in the lambda expression used with the filter or filterIndexed function.

For example, let's remove the numbers 2 and 4 from the array:

val filteredArray = numbers.filter { it != 2 && it != 4 }

In this code, the lambda expression checks if the current element is not equal to 2 and also not equal to 4. If the condition is true, the element is included in the filteredArray.

Step 5: Modify the Original Array​

If you want to modify the original array instead of creating a new filtered array, you can use the removeAll function.

For example, let's remove the numbers 2 and 4 from the original array:

numbers.removeAll { it == 2 || it == 4 }

In this code, the lambda expression checks if the current element is equal to 2 or 4. If the condition is true, the element is removed from the original array.

That's it! You've learned how to remove specific elements from an array in Kotlin.