Searching in Arrays
The indexOf() Method
The indexOf()
method returns the first index of the item that matches the provided value. If no matches were found the method will return -1
.
const colors = ['red', 'orange', 'red', 'purple', 'blue']
console.log(colors.indexOf('purple')) // 3
console.log(colors.indexOf('red')) // 0
console.log(colors.indexOf('black')) // -1
Also see the lastIndexOf()
method for returning the last index of the item that matches the provided value.
The includes() Method
The includes()
method determines wether an array includes the specified value, and returns true
or false
appropriately.
const colors = ['red', 'orange', 'red', 'purple', 'blue']
console.log(colors.includes('purple')) // true
console.log(colors.includes('red')) // true
console.log(colors.includes('black')) // false
The find() Methods
The find()
method returns the value of the first item in the array that satisfies the provided testing function. If no item passes the test, undefined is returned.
const numbers = [5, 12, 15, 8]
console.log(numbers.find(item => item > 10)) // 12
console.log(numbers.find(item => item > 20)) // undefined
NOTE
The above example lines 3 and 4 uses Arrow Function
expression.
item => item > 10
can also be written as function (item){ return item > 10 }
Also see the findIndex()
method, which returns the index of a found element in the array instead of its value.