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
transformin Scala:edit:
If you want filter and map separated, use a
view: