JavaScript Array Type

Search

We can use the find, findIndex, indexOf and lastIndexOf to search for an element that are either a specific value or satisfies some condition.

The indexOf and lastIndexOf methods expects us to know the exact value we're looking for. They return the index of the given element if was within the array or -1 if it wasn't.

The find and findIndex methods expects us to specify a predicate function which is used to search for the correct element. find returns the first element that satisfies the predicate or undefined if no elements satisfy the testing function. findIndex, on the other hand, returns the index or -1.

Code example: indexOf

const arr = [1, 2, 3, 4]
const oneInd = arr.indexOf(1)
console.log(one) // 0
const fiveInd = arr.indexOf(5)
console.log(fiveInd) // -1

Code example: find

const arr = [1, 2, 30, 40]
const greaterThanTwo = arr.find(x => x > 2)
console.log(greaterThanTwo) // 30
const greaterThanFifty = arr.find(x => x > 50)
console.log(greaterThanFifty) // undefined