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?
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.
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.
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.
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.
filterIndexed
function is suited exactly for this case:
array.filterIndexed { index, value -> index % n == 0 }
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 }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With