Searching in Arrays

The indexOf() Method

The indexOf()open in new window 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()open in new window method for returning the last index of the item that matches the provided value.

The includes() Method

The includes()open in new window 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()open in new window 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 Functionopen in new window expression.

item => item > 10 can also be written as function (item){ return item > 10 }

Also see the findIndex()open in new window method, which returns the index of a found element in the array instead of its value.