13

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?

2
  • Just a comment, the code above is just Java masked in a Kotlin file, my recommendation is to you try to look Kotlin code in a different way, this will help you to use everything that we have available. Commented Oct 21, 2017 at 19:55
  • 1
    Absolutely. This is why I asked the question. Commented Oct 21, 2017 at 19:58

2 Answers 2

36

filterIndexed function is suited exactly for this case:

array.filterIndexed { index, value -> index % n == 0 }
Sign up to request clarification or add additional context in comments.

Comments

13

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 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.