This article explores different ways to remove all occurrences of a given element from an array in Kotlin.

Since arrays are fixed-sized in Kotlin, you can’t remove an element from it. However, you can create a copy of the original array, which excludes the specified element. We can do this in several ways:

1. Using filter() function

The trick is to filter all occurrences of the given element using the filter() function and return the list as an array using the toTypedArray() function.

Download Code

2. Using MutableList

The idea is to iterate over the array and insert each element that doesn’t match the specified element in a new MutableList instance. Finally, return the list as an array using toTypedArray() function.

Download Code

 
Another plausible way is to insert all array elements into a MutableList and then use the removeAll() function to remove all occurrences of the given key from the list.

Download Code

That’s all about removing all occurrences of the specified element from an array in Kotlin.