In this lesson I introduce you these 5 methods which can all help in searching an item in the array:
indexOf()
lastIndexOf()
find()
findIndex()
includes()
It’s great to know them all, but includes()
is the most recently (2016) introduced one and I think the one you should use the most. Let’s see them in details.
indexOf()
a.indexOf()
Returns the index of the first matching item found, or -1
if not found
lastIndexOf()
a.lastIndexOf()
Returns the index of the last matching item found, or -1 if not found
find()
a.find((element, index, array) => {
//return true or false
})
Returns the first item that returns true. Returns undefined if not found.
A commonly used syntax is:
a.find(x => x.id === my_id)
The above line will return the first element in the array that has id === my_id
.
findIndex()
findIndex
returns the index of the first item that returns true, and if not found, it returns undefined
:
a.findIndex((element, index, array) => {
//return true or false
})
includes()
includes()
returns a true boolean value if the element is included in the array, or false otherwise:
if (![1,2].includes(3)) {
console.log('Not found')
}