LEARNING JAVASCRIPT - Trang 160

Array Searching

If you want to find something in an array, you have a few choices. We’ll start with the

humble

indexOf

, which has been available in JavaScript for some time.

indexOf

sim‐

ply returns the index of the first element it finds that is strictly equal to what you’re

looking for (there is a corresponding

lastIndexOf

that searches in the other direc‐

tion, and returns the last index that matches what you’re looking for). If you only

want to search a portion of an array, you can specify an optional start index. If

indexOf

(or

lastIndexOf

) returns –

1

, it wasn’t able to find a match:

const

o

=

{

name

:

"Jerry"

};

const

arr

=

[

1

,

5

,

"a"

,

o

,

true

,

5

, [

1

,

2

],

"9"

];

arr

.

indexOf

(

5

);

// returns 1

arr

.

lastIndexOf

(

5

);

// returns 5

arr

.

indexOf

(

"a"

);

// returns 2

arr

.

lastIndexOf

(

"a"

);

// returns 2

arr

.

indexOf

({

name

:

"Jerry"

});

// returns -1

arr

.

indexOf

(

o

);

// returns 3

arr

.

indexOf

([

1

,

2

]);

// returns -1

arr

.

indexOf

(

"9"

);

// returns 7

arr

.

indexOf

(

9

);

// returns -1

arr

.

indexOf

(

"a"

,

5

);

// returns -1

arr

.

indexOf

(

5

,

5

);

// returns 5

arr

.

lastIndexOf

(

5

,

4

);

// returns 1

arr

.

lastIndexOf

(

true

,

3

);

// returns -1

Next up is

findIndex

, which is similar to

indexOf

in that it returns an index (or –

1

if

there’s no match).

findIndex

is more flexible, though, in that you can provide a func‐

tion that determines if an element is a match (

findIndex

doesn’t have an option to

start at an arbitrary index, nor is there a corresponding

findLastIndex

):

const

arr

=

[{

id

:

5

,

name

:

"Judith"

}, {

id

:

7

,

name

:

"Francis"

}];

arr

.

findIndex

(

o

=>

o

.

id

===

5

);

// returns 0

arr

.

findIndex

(

o

=>

o

.

name

===

"Francis"

);

// returns 1

arr

.

findIndex

(

o

=>

o

===

3

);

// returns -1

arr

.

findIndex

(

o

=>

o

.

id

===

17

);

// returns -1

find

and

findIndex

are great if you’re looking for the index of an element. But what

if you don’t care about the index of the element, but just want the element itself?

find

is like

findIndex

in that it allows you to specify a function to find what you’re look‐

ing for, but it returns the element itself instead of the index (or

null

if no such ele‐

ment was found):

const

arr

=

[{

id

:

5

,

name

:

"Judith"

}, {

id

:

7

,

name

:

"Francis"

}];

arr

.

find

(

o

=>

o

.

id

===

5

);

// returns object { id: 5, name: "Judith" }

arr

.

find

(

o

=>

o

.

id

===

2

);

// returns null

136 | 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.