algorithmscala

What's the best way to write `indexBy` in Scala?


Underscore.js has a function indexBy which does the following:

Given a list, and an iteratee function that returns a key for each element in the list (or a property name), returns an object with an index of each item. Just like groupBy, but for when you know your keys are unique.

var stooges = [{name: 'moe', age: 40}, {name: 'larry', age: 50}, {name: 'curly', age: 60}];
_.indexBy(stooges, 'age');
=> {
  "40": {name: 'moe', age: 40},
  "50": {name: 'larry', age: 50},
  "60": {name: 'curly', age: 60}
}

What's the best way to write this in Scala?


Solution

  • final case class Stooge(name: String, age: Int)
    
    val stooges = Seq(Stooge("moe", 40), Stooge("larry", 50))
    
    val result = stooges.map(s => s.age -> s).toMap
    
    println(result)
    // Map(40 -> Stooge(moe,40), 50 -> Stooge(larry,50))