const
words
=
[
"Beachball"
,
"Rodeo"
,
"Angel"
,
"Aardvark"
,
"Xylophone"
,
"November"
,
"Chocolate"
,
"Papaya"
,
"Uniform"
,
"Joker"
,
"Clover"
,
"Bali"
];
const
alphabetical
=
words
.
reduce
((
a
,
x
)
=>
{
if
(
!
a
[
x
[
0
]])
a
[
x
[
0
]]
=
[];
a
[
x
[
0
]].
push
(
x
);
return
a
; }, {});
This example is a little more involved, but the principle is the same. For every ele‐
ment in the array, the function checks the accumulator to see if it has a property for
the first letter in the word; if not, it adds an empty array (when it sees
"Beachball",
there is no property
a.B
, so it creates one whose value is an empty array). It then adds
the word to the appropriate array (which may have just been created), and finally, the
accumulator (
a
) is returned (remember the value you return is used as the accumula‐
tor for the next element in the array).
Another example is computational statistics. For example, to calculate the mean and
variation of a data set:
const
data
=
[
3.3
,
5
,
7.2
,
12
,
4
,
6
,
10.3
];
// Donald Knuth's algorithm for calculating variance:
// Art of Computer Programming, Vol. 2: Seminumerical Algorithms, 3rd Ed., 1998
const
stats
=
data
.
reduce
((
a
,
x
)
=>
{
a
.
N
++
;
let
delta
=
x
-
a
.
mean
;
a
.
mean
+=
delta
/
a
.
N
;
a
.
M2
+=
delta
*
(
x
-
a
.
mean
);
return
a
;
}, {
N
:
0
,
mean
:
0
,
M2
:
0
});
if
(
stats
.
N
>
2
) {
stats
.
variance
=
stats
.
M2
/
(
stats
.
N
-
1
);
stats
.
stdev
=
Math
.
sqrt
(
stats
.
variance
);
}
Again, we’re leveraging an object as the accumulator because we need multiple vari‐
ables (
mean
and
M2
, specifically: we could have used the index argument—minus one
—in place of
N
if we had wanted to).
We’ll see one last (and very silly) example to drive home the flexibility of
reduce
by
using an accumulator type we haven’t used yet—a string:
const
words
=
[
"Beachball"
,
"Rodeo"
,
"Angel"
,
"Aardvark"
,
"Xylophone"
,
"November"
,
"Chocolate"
,
"Papaya"
,
"Uniform"
,
"Joker"
,
"Clover"
,
"Bali"
];
const
longWords
=
words
.
reduce
((
a
,
w
)
=>
w
.
length
>
6
?
a
+
" "
+
w
:
a
,
""
).
trim
();
// longWords: "Beachball Aardvark Xylophone November Chocolate Uniform"
Here we’re using a string accumulator to get a single string containing all words
longer than six letters. As a reader’s exercise, try rewriting this using
filter
and
join
142 | Chapter 8: Arrays and Array Processing