Omid
Omid

Reputation: 1989

Scala: Get specific elements by a sequence of indices

How can I get specific elements of an array by having the sequence of indices, I do it now by following:

val indices = Array(1,3,3,2)
val a = Array("a","b","c","d","e","f")
indices.map(a(_))

the problem is if I want to make it a safe search I have to check a.contains or modify the indices. sometimes the indices is to big and I can not modify it fast. What is the best time/space solution?

Upvotes: 1

Views: 3798

Answers (4)

Lucas Meier
Lucas Meier

Reputation: 449

If you don't want to use collect you may try :

val indices = Array(1, 2, 3, 2)
val arr = Array("a", "b", "c", "d")
val res = for (i <- indices) yield arr(i)

Upvotes: 0

elm
elm

Reputation: 20405

Using flatMap where out of bound indexes are mapped onto None, like this,

indices.flatMap(i => if (i < a.length) Some(a(i)) else None)

Simpler forms with flatMap,

indices.flatMap(i => Some(a(i)))
res: Array(b, d, d, c)

indices.flatMap(a(_))
res: Array(b, d, d, c)

Upvotes: 0

Eastsun
Eastsun

Reputation: 18859

Here it is:

scala> val indices = Array(1, 2, 3, 2, 100, -100, 4, 5)
indices: Array[Int] = Array(1, 2, 3, 2, 100, -100, 4, 5)

scala> val arr = Array("a", "b", "c", "d")
arr: Array[String] = Array(a, b, c, d)

scala> indices collect arr
res1: Array[String] = Array(b, c, d, c)

Upvotes: 6

Dennis Traub
Dennis Traub

Reputation: 51624

Assuming you just want to ignore every out-of-bounds-index you could just use a filter before mapping:

indices.filter(_ < a.length).map(a(_))

Upvotes: 0

Related Questions