Kotlin Array.filterIndexed()

Kotlin Array.filterIndexed() function

In Kotlin, the Array.filterIndexed() function is used to create a new array containing only the elements that satisfy a given predicate. It allows you to filter elements based on both their values and indices.

This function is useful when you need to consider both the values and positions of elements in the array during the filtering process.

In this tutorial, we’ll explore the syntax of the Array.filterIndexed() function and provide examples of its usage in Kotlin Array.

Syntax

The syntax of the Array.filterIndexed() function is as follows:

inline fun <T> Array<out T>.filterIndexed(
    predicate: (index: Int, T) -> Boolean
): List<T>

where

ParameterDescription
predicateA lambda function that takes an index and the corresponding element from the array and returns true or false based on the condition to be satisfied.
Parameter of Array filterIndexed() function

Examples for Array filterIndexed() function

1. Filtering Elements at Odd Indices

In this example, we’ll use filterIndexed() to obtain a new array containing elements at odd indices from a give array of strings wordsArray.

Kotlin Program

fun main() {
    val wordsArray = arrayOf("apple", "banana", "cherry", "fig", "mango")

    // Filtering elements at odd indices
    val oddIndexedNumbers = wordsArray.filterIndexed { index, _ -> index % 2 != 0 }

    // Printing the original array and the result
    println("Given Array\n${wordsArray.joinToString(", ")}\n")
    println("Elements at Odd Indices\n${oddIndexedNumbers.joinToString(", ")}")
}

Output

Given Array
apple, banana, cherry, fig, mango

Elements at Odd Indices
banana, fig

2. Filtering Elements with Index and Value

In this example, we’ll use filterIndexed() to obtain a new array containing elements that are greater than their index from a given array of integers numbersArray.

Kotlin Program

fun main() {
    val numbersArray = arrayOf(5, 1, 7, 3, 8, 2, 4, 6)

    // Filtering elements greater than their index
    val greaterThanIndex = numbersArray.filterIndexed { index, value -> value > index }

    // Printing the original array and the result
    println("Numbers Array\n${numbersArray.joinToString(", ")}\n")
    println("Elements Greater Than Index\n${greaterThanIndex.joinToString(", ")}")
}

Output

Numbers Array
5, 1, 7, 3, 8, 2, 4, 6

Elements Greater Than Index
5, 7, 8

Summary

In this tutorial, we’ve covered the Array.filterIndexed() function in Kotlin arrays, its syntax, and how to use it to create a new array containing elements based on both their values and indices.