LEARNING JAVASCRIPT - Trang 163

This example is a little more sophisticated, but it demonstrates the power of the

map

function. Here, we’re using not just the element itself (

x

), but its index (

i

). We need

the index because we want to correlate elements in

items

with elements in

prices

according to their index. Here,

map

is converting an array of strings to an array of

objects, by pulling in information from a separate array. (Note that we had to sur‐

round the object in parentheses; without the parentheses, the arrow notation will take

the curly braces to denote a block.)

filter

, as the name implies, is designed to remove unwanted things from an array.

Like

map

, it returns a new array with elements removed. What elements? Again, that’s

completely up to you. If you guessed that we’re providing a function to determine

which elements to remove, you’re catching on. Let’s see some examples:

// create a deck of playing cards

const

cards

=

[];

for

(

let

suit

of

[

'H'

,

'C'

,

'D'

,

'S'

])

// hearts, clubs, diamonds, spades

for

(

let

value

=

1

;

value

<=

13

;

value

++

)

cards

.

push

({

suit

,

value

});

// get all cards with value 2:

cards

.

filter

(

c

=>

c

.

value

===

2

);

// [

// { suit: 'H', value: 2 },

// { suit: 'C', value: 2 },

// { suit: 'D', value: 2 },

// { suit: 'S', value: 2 }

// ]

// (for the following, we will just list length, for compactness)

// get all diamonds:

cards

.

filter

(

c

=>

c

.

suit

===

'D'

);

// length: 13

// get all face cards

cards

.

filter

(

c

=>

c

.

value

>

10

);

// length: 12

// get all face cards that are hearts

cards

.

filter

(

c

=>

c

.

value

>

10

&&

c

.

suit

===

'H'

);

// length: 3

Hopefully you can start to see how

map

and

filter

can be combined to great effect.

For example, let’s say we want to create short string representation of the cards in our

deck. We’ll use the Unicode code points for the suits, and we’ll use “A,” “J,” “Q,” and

“Q” for ace and the face cards. Because the function that constructs this is a bit long,

we’ll go ahead and create it as a separate function instead of trying to use an anony‐

mous function:

function

cardToString

(

c

) {

const

suits

=

{

'H'

:

'\u2665'

,

'C'

:

'\u2663'

,

'D'

:

'\u2666'

,

'S'

:

'\u2660'

};

const

values

=

{

1

:

'A'

,

11

:

'J'

,

12

:

'Q'

,

13

:

'K'

};

// constructing values each time we call cardToString is not very

// efficient; a better solution is a reader's exercise

The Fundamental Array Operations: map and filter | 139

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.