jOasis
jOasis

Reputation: 394

(Value,Index) pair range filter based on index

I am looking for a way to get all the pair from the given data structure Array[Array[(String, Int)]] based on range criteria.

To clarify more: consider the example:

val block= Array(Array(("foo",0),("bar",1),("foobar",2),("barfoo",3)),Array(("FOO",0),("BAR",1),("FOOBAR",2),("BARFOO",3),("FOOFOO",4)))

I would like to get the String Array from index 3 onwards like this:

Array(Array("barfoo"),Array("BARFOO", "FOOFOO"))

Tried like this:

blocks.filter{case (k,v) => v>=3}.keys

It cannot be constructed because the required type needs to be Array[(String, Int)] in order to do filter. I know I am missing the map before but just can't seem to get around.

Upvotes: 0

Views: 128

Answers (2)

James Whiteley
James Whiteley

Reputation: 3474

You can drop the elements if the second part of the Tuple is < 3:

scala> val block = Array(
     |   Array(("foo",0),("bar",1),("foobar",2),("barfoo",3)),
     |   Array(("FOO",0),("BAR",1),("FOOBAR",2),("BARFOO",3),("FOOFOO",4))
     | )
block: Array[Array[(String, Int)]] = Array(Array((foo,0), (bar,1), (foobar,2), (barfoo,3)), Array((FOO,0), (BAR,1), (FOOBAR,2), (BARFOO,3), (FOOFOO,4)))

scala> block.map(_.dropWhile(_._2 < 3).map(_._1).toArray)
res0: Array[Array[String]] = Array(Array(barfoo), Array(BARFOO, FOOFOO))

Upvotes: 0

vindev
vindev

Reputation: 2280

As the type of block is Array[Array[(String, Int)]], so before using filter you need to use map operation. Using block.map(_.filter(_._2 >= 3).map(_._1)) will give you the desired result.

Upvotes: 2

Related Questions