LEARNING JAVASCRIPT - Trang 165

3. The function is called for the third array element (

2

).

a

has the initial value

12

,

and

x

has the value

2

. The function returns the sum of

a

and

x

(

14

).

4. The function is called for the fourth and final array element (

4

).

a

has the value

14

, and

x

has the value

4

. The function returns the sum of

a

and

x

(

18

), which is

the return value of

reduce

(which is then assigned to

sum

).

The astute reader might realize that—in this very simple example—we don’t even

need to assign to

a

; what’s important is what’s returned from the function (remember

that the arrow notation doesn’t require an explicit

return

statement), so we could

have just returned

a + x

. However, in more sophisticated examples, you might want

to do more with the accumulator, so it’s a good habit to get into to modify the accu‐

mulator inside the function.
Before we move on to more interesting applications of

reduce

, let’s consider what

happens if the initial accumulator is

undefined

. In this case,

reduce

takes the first

array element as the initial value and starts calling the function with the second ele‐

ment. Let’s revisit our example, and omit the initial value:

const

arr

=

[

5

,

7

,

2

,

4

];

const

sum

=

arr

.

reduce

((

a

,

x

)

=>

a

+=

x

);

1. The (anonymous) function is called for the second array element (

7

).

a

has the

initial value

5

(the first array element), and

x

has the value

7

. The function

returns the sum of

a

and

x

(

12

), which will become the value of

a

in the next step.

2. The function is called for the third array element (

2

).

a

has the initial value

12

,

and

x

has the value

2

. The function returns the sum of

a

and

x

(

14

).

3. The function is called for the fourth and final array element (

4

).

a

has the value

14

, and

x

has the value

4

. The function returns the sum of

a

and

x

(

18

), which is

the return value of

reduce

(which is then assigned to

sum

).

You can see that there is one fewer step, but the outcome is the same. In this example

(and in any case where the first element can serve as the initial value of the accumula‐

tor), we can benefit from omitting the initial value.
Using an atomic value (a number or string) as the accumulator is a common use for

reduce

, but using an object as an accumulator is a very powerful (and often over‐

looked) method. For example, if you have an array of strings, and you want to group

the strings into alphabetic arrays (A words, B words, etc.), you can use an object:

Array Magic: reduce | 141

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.