Loops/Foreach: Difference between revisions
→. map() and .reduce() allow for easier composition of nested functions than .forEach()
Line 949:
=={{header|JavaScript}}==
For arrays in ES5, we can use '''Array.forEach()''':
<lang JavaScript>"alpha beta gamma delta".split(' ').forEach(
Line 962:
gamma
delta</pre>
though it will probably be more natural – dispensing with side-effects, and allowing for easier composition of nested functions – to simply use '''Array.map()''',
<lang JavaScript>console.log("alpha beta gamma delta".split(' ').map(
function (x) {
return x.toUpperCase(x);
}
).join('\n'));</lang>
Output:
<pre>ALPHA
BETA
GAMMA
DELTA</pre>
or, more flexibly, and with greater generality, obtain an accumulating fold from '''Array.reduce()'''
<lang JavaScript>console.log(
"alpha beta gamma delta".split(' ').reduce(
function (a, x, i, lst) {
return lst.length - i + '. ' + x + '\n' + a;
}, ''
)
)</lang>
Output:
<pre>1. delta
2. gamma
3. beta
4. alpha</pre>
More generally, the following works for any object, including an array. It iterates over the keys of an object.
|