LEARNING JAVASCRIPT - Trang 164

for

(

let

i

=

2

;

i

<=

10

;

i

++

)

values

[

i

]

=

i

;

return

values

[

c

.

value

]

+

suits

[

c

.

suit

];

}

// get all cards with value 2:

cards

.

filter

(

c

=>

c

.

value

===

2

)

.

map

(

cardToString

);

// [ "2

", "2", "2", "2" ]

// get all face cards that are hearts

cards

.

filter

(

c

=>

c

.

value

>

10

&&

c

.

suit

===

'H'

)

.

map

(

cardToString

);

// [ "J

", "Q", "K" ]

Array Magic: reduce

Of all the array methods, my favorite is

reduce

. Where

map

transforms each element

in the array,

reduce

transforms the entire array. It’s called

reduce

because it’s often

used to reduce the array to a single value. For example, summing the numbers in an

array or calculating the average is a way of reducing the array to a single value. How‐

ever, the single value

reduce

provides can be an object or another array—as a matter

of fact,

reduce

is capable of reproducing the functionality of

map

and

filter

(or, for

that matter, any other array function we’ve discussed).

reduce

—like

map

and

filter

—allows you to provide a function that controls the out‐

come. In the callbacks we’ve dealt with heretofore, the first element passed into the

callback is always the current array element. Not so with

reduce

: the first value is an

accumulator, which is what the array is being reduced to. The rest of the arguments

are what you would expect: the current array element, the current index, and the

array itself.
In addition to taking a callback,

reduce

takes an (optional) initial value for the accu‐

mulator. Let’s look at a simple example—summing the numbers in an array:

const

arr

=

[

5

,

7

,

2

,

4

];

const

sum

=

arr

.

reduce

((

a

,

x

)

=>

a

+=

x

,

0

);

The function being passed into

reduce

takes two parameters: the accumulator (

a

) and

the current array element (

x

). In this example, we’re starting the accumulator off with

a value of

0

. Because this is our first experience with

reduce

, let’s walk through the

steps JavaScript takes so we understand how it’s working:

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

5

).

a

has the ini‐

tial value

0

, and

x

has the value

5

. The function returns the sum of

a

and

x

(

5

),

which will become the value of

a

in the next step.

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

7

).

a

has the initial value

5

(passed in from the previous step), 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.

140 | Chapter 8: Arrays and Array Processing

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.