In this article, I will introduce some ways I use the most to search through an array to you. Let’s dive right in!

Array.indexOf()

indexOf() uses strict comparison to find an item and then returns the index of that item.

For example:

let languages = [‘Java’, ‘Kotlin’, ‘Python’, ‘Ruby’, ‘JavaScript’];

console.log(languages.indexOf(‘Ruby’)); // 3
console.log(languages.indexOf(‘Golang’)); // -1

If the value is not found in the array, -1 will be returned.

indexOf() returns the index of the first found item starting the first position. If you want to search from the last position, take lastIndexOf()

let numbers = [1, 6, 3, 1, 5];

console.log(numbers.lastIndexOf(1)); // 3
console.log(numbers.indexOf(1)); // 0

#programming #javascript

How to Search in an Array in JavaScript
1.10 GEEK