Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Kotlin filter lambda array using iteration index

I would like to filter an array into an array of every nth item. For examples:

fun getNth(array: Array<Any>, n: Int): Array<Any> {
    val newList = ArrayList<Any>()
    for  (i in 0..array.size) {
        if (i % n == 0) {
            newList.add(array[i])
        }
    }
    return newList.toArray()
}

Is there an idiomatic way to do this using for example Kotlin's .filter() and without A) provisioning a new ArrayList and B) manually iterating with a for/in loop?

like image 232
Nate Vaughan Avatar asked Oct 21 '17 19:10

Nate Vaughan


People also ask

How do I filter an array in Kotlin?

To filter collections by negative conditions, use filterNot() . It returns a list of elements for which the predicate yields false . There are also functions that narrow the element type by filtering elements of a given type: filterIsInstance() returns collection elements of a given type.

What is the use of filter {} in Kotlin?

The basic function is filter() to be used for filtering. When filter() function is called with a predicate, it returns the collection elements that match the predicate.

How do you access the index of a list in Kotlin?

In any lists, you can find the position of an element using the functions indexOf() and lastIndexOf() . They return the first and the last position of an element equal to the given argument in the list.

How do you use forEachIndexed in Kotlin?

Example: Using forEachIndexed() nstead of using forEach() loop, you can use the forEachIndexed() loop in Kotlin. forEachIndexed is an inline function which takes an array as an input and its index and values are separately accessible.


2 Answers

filterIndexed function is suited exactly for this case:

array.filterIndexed { index, value -> index % n == 0 }
like image 84
Ilya Avatar answered Oct 03 '22 15:10

Ilya


Use Array.withIndex():

https://kotlinlang.org/api/latest/jvm/stdlib/kotlin.collections/with-index.html:

array.withIndex().filter { (i, value) -> i % n == 0 }.map { (i, value) -> value }
like image 35
Alexey Romanov Avatar answered Sep 30 '22 15:09

Alexey Romanov