bugl
bugl
HomeLearnPatternsSearch
HomeLearnPatternsSearch

Loading lesson path

Learn/JavaScript/Working with Data
JavaScript•Working with Data

JavaScript Array Search

Concept visual

JavaScript Array Search

Pointer walk
two pointers
leftright102132436485116
left=0
right=6
1
3

Start at both ends

Array Search Methods

Array indexOf()

Array lastIndexOf()

Array includes()

Array find()

Array findIndex()

Array findLast()

Array findLastIndex()

Complete JavaScript Array Reference

See Also:

JavaScript Array Tutorial

JavaScript Basic Array Methods

JavaScript Array Sort Methods

JavaScript Array Iteration Methods

JavaScript Array Reference

JavaScript Array indexOf()

The indexOf()

method searches an array for an element value and returns its position.

Note:

The first item has position 0, the second item has position 1, and so on.

Example

Search an array for the item "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.indexOf("Apple") + 1;
Syntax array.indexOf(

item, start ) item Required. The item to search for. start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the end.

Formula

Array.indexOf() returns - 1 if the item is not found.
If the item is present more than once, it returns the position of the first occurrence.

JavaScript Array lastIndexOf()

Array.lastIndexOf() is the same as Array.indexOf(), but returns the position of the last occurrence of the specified element.

Example

Search an array for the item "Apple":

const fruits = ["Apple", "Orange", "Apple", "Mango"];
let position = fruits.lastIndexOf("Apple") + 1;
Syntax array.lastIndexOf(

item, start ) item Required. The item to search for start Optional. Where to start the search. Negative values will start at the given position counting from the end, and search to the beginning

JavaScript Array includes()

ECMAScript 2016 introduced

Array.includes() to arrays. This allows us to check if an element is present in an array (including NaN, unlike indexOf).

Example

const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.includes("Mango"); // is true
Syntax array.includes(

Formula

search - item

) Array.includes() allows to check for NaN values. Unlike Array.indexOf().

Previous

JavaScript Get Date Methods

Next

JavaScript Set Logic