Searching Through an Array in JavaScript

548
SHARES
2.5k
VIEWS

Let’s discuss how we can search an array for a specific value and get the array element index if found. To accomplish this, we will use the Array methods indexOf() and lastIndexOf():

let fruits = new Array("mango","apple","banana","orange","pineapple");
console.log(fruits.indexOf("banana")); // prints 2

Though support for both indexOf() and lastIndexOf() has existed in browsers for some time, their use wasn’t standardized until the release of ECMAScript 5. Both methods take a search value that is then compared to every element in the array. If the value is found, both return an index representing the array element. If the value is not found, –1 is returned. The indexOf() method returns the first one found, the lastIndexOf() returns the last one found:

let fruits = new Array("mango","apple","banana","orange","pineapple");

console.log(animals.indexOf("apple")); // prints 1
console.log(animals.lastIndexOf("orange")); // prints 3

Both methods can take a starting index, setting where the search is going to start:

let fruits = new Array("mango","apple","banana","orange","pineapple", "strawberry");

console.log(fruits.indexOf("apple",2)); // prints 5
console.log(fruits.lastIndexOf("apple",4)); // prints 1

If your interest goes beyond just finding an exact match, you can use the ECMAScript 6 (ES 6) Array method findIndex(), providing a function that tests each array value, returning the index of the array element when the test is successful.

An example use of findIndex() is the following, using the new method to find an array element whose value equals or exceeds 100:

var nums = [2, 4, 19, 12, 45, 53, 7, 4, 1];

var over = nums.findIndex(function(element) {
  return (element >= 100);
});

console.log(nums[over]);

A comparable ES 6 Array method is find(), which does the same process but returns the value of the element that successfully passes the given test. Both methods take a callback function, and an optional second argument to act as this in the function. The callback function has three arguments, the array element, index, and array, itself, but only the first is required. Neither method mutates the original array.

Leave a Reply

Your email address will not be published. Required fields are marked *

Trending