Lesson 9 of 15
Map & Filter
Map & Filter
map transforms each element; filter keeps only matching elements:
val nums = List(1, 2, 3, 4, 5, 6)
val evens = nums.filter(x => x % 2 == 0)
println(evens) // List(2, 4, 6)
val doubled = nums.map(x => x * 2)
println(doubled) // List(2, 4, 6, 8, 10, 12)
Chaining
val result = nums.filter(x => x % 2 == 0).map(x => x * x)
println(result) // List(4, 16, 36)
Your Task
Write a function doubleEvens that takes a List[Int] and returns a new list containing only the even numbers, each doubled.
JS Transpiler loading...
Loading...
Click "Run" to execute your code.