I want to return an array that that maps some filtered elements - but I want to keep the non-filtered elements where they are. i.e. Is there an easy way to do this?:
array
.filter(
function(element){
// some test
}
)
.map(
function(element){
// some mapping
}
)
The closest solution I've come up with is something along the lines of:
array
.map(
function(value, index){
if (<test>) {
return <mapping>(value);
}
}
)
but I feel this somewhat breaks the spirit of functional programming.
I'm not asking for a specific language implementation, although an example in Scala or JavaScript would be nice.
EDIT: Here's a concrete example of what I'm looking for:
[1,2,3,4,11,12]
Mapping all elements to element*10, for all elements in array which are greater than 10, should yield
[1,2,3,4,110,120]
EDIT2: I apologize for using the word "mutate." I did not mean mutate the original array - I was thinking more along the lines of mutating a copy of the array.
It's not really going to be functional if you're using a mutable collection. But you can use transform
in Scala:
scala> val a = Array(1,2,3,4,11,12)
a: Array[Int] = Array(1, 2, 3, 4, 11, 12)
scala> a.transform {i => if(i > 10) i * 10 else i}
res10: scala.collection.mutable.WrappedArray[Int] = WrappedArray(1, 2, 3, 4, 110, 120)
edit:
If you want filter and map separated, use a view
:
scala> a
res22: Array[Int] = Array(1, 2, 3, 4, 11, 12)
scala> a.view.filter(_ > 10).transform(_ * 10)
res23: scala.collection.mutable.IndexedSeqView[Int,Array[Int]] = SeqViewF(...)
scala> a
res24: Array[Int] = Array(1, 2, 3, 4, 110, 120)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With