Is there a way, in Javascript (ES2015), to map only part of a array?
E.g.:
let m = someArray.map(function(n){ if(n===0) return n+1; }
That's it, it would return a mapped array that has less elements than the original one.
Is that something that we could accomplish out of the box with some functional programming technique?
Is there a way, in Javascript (ES2015), to map only part of a array?
E.g.:
let m = someArray.map(function(n){ if(n===0) return n+1; }
That's it, it would return a mapped array that has less elements than the original one.
Is that something that we could accomplish out of the box with some functional programming technique?
Share Improve this question edited Sep 29, 2015 at 22:33 imtheman 4,8431 gold badge31 silver badges31 bronze badges asked Sep 29, 2015 at 22:31 DraconarDraconar 1,1951 gold badge17 silver badges37 bronze badges 6 | Show 1 more comment4 Answers
Reset to default 9Maps changing the number of elements are icky. It's better to filter first, then map:
let arr2 = arr.filter(e => e === 0).map(e => e + 1);
This is easy with array comprehensions, which were introduced by the ECMAScript 6 draft, but will be postponed to ES7:
let m = [for (n of someArray) if (n===0) n+1]
You won't be able to skip unneeded elements with native Array.prototype.map(). But there's always Array.prototype.reduce() to save the day:
let m = someArray.reduce(function(mem, el) {
if (el === 0) {
mem.push(el + 1);
}
return mem;
}, []);
Array iteration methods are (except for deprecated edge cases1) a concise way of expressing what you'd do with a loop (for(i = 0; i < arr.length; i++) { doSomething(arr[i]) }
). When the meaning of the method name is no longer representative, you acheive the exact opposite - instead of using a method that describe the operation, you're using one that doesn't and confuse the reader.
More so, not using this group of methods is more performant. This mostly happens because invoking a function is "expensive".
To use the methods, while being concise, see Bartek's answer.
Alternatively, simply use a loop:
let m = [];
for(v of someArray) {
if(v !== 0) {
m.push(v + 1);
}
}
1 When these methods are called, the length of the array is sampled, and any element added beyond this length from within the callback is not visited.
.filter()
and.map()
? – Pointy Commented Sep 29, 2015 at 22:32.reduce()
could do that, if JS allows an array as initial value. Only needs 1 cycle then. – Rudie Commented Sep 29, 2015 at 22:33.filter
onn === 0
then.map
– dievardump Commented Sep 29, 2015 at 22:37