Four Methods to Search Through Arrays in JavaScript

Introduction

In JavaScript, you will often be working with data that is stored in Arrays. A common task will be searching the array to find if it contains a value (or values) that satisfies certain search criteria. Depending on the task at hand, you may be interested in a boolean value for confirmation, an index for the position of the value in the array, or a separate array containing all the search results.

Prior to ECMAScript 6, you probably would have used a for loop to iterate through all the items in the array and perform operations on each item. Now there are several built-in utility methods that solve some of the common tasks for searching for values in an array.

In this article, you will learn about Array.includes()Array.indexOfArray.find(), and Array.filter.

Prerequisites

If you would like to follow along with this article, you will need:

Using includes()

The includes() method returns either a true or a false if a value exists in an array or not.

This is the basic syntax:

arr.includes(valueToFind[, fromIndex]);

 Copy

The first parameter, valueToFind, is the value to match in the array. The second parameter, fromIndex, is optional and sets the index from which to begin comparisons. The default is 0, so the entire array is searched.

Here is a sample array of alligator facts:

const alligatorFacts = ["thick scales", 80, "4 foot tail", "rounded snout", 80];

 Copy

Then use includes() to check if the string "thick scales" exists in the array:

alligatorFacts.includes("thick scales");

 Copy

This code would return true, because the string exists in the array.

If you were to add a fromIndex parameter so the comparison occurs after "thick scales", it would return false:

alligatorFacts.includes("thick scales", 1);

 Copy

Now, there are a few important things to notice. This .includes() method uses strict comparison.

alligatorFacts.includes(80);

 Copy

This code will return true because the numeric value 80 is in the array.

alligatorFacts.includes('80');

 Copy

This code will return false because the string value '80' is not in the array.

includes() is helpful for use cases where you only need to know if a value exists in an array.

Using indexOf()

The indexOf() method returns the first index of a value in an array. If there is no match, the method returns -1.

This is the basic syntax:

arr.indexOf(searchElement[, fromIndex])

 Copy

Let’s revisit the sample array of alligator facts:

const alligatorFacts = ["thick scales", 80, "4 foot tail", "rounded snout", 80];

 Copy

Then use indexOf() to return the first index of the string "rounded snout":

alligatorFacts.indexOf("rounded snout");

 Copy

The index of the string "rounded snout" – 4 – will be returned.

alligatorFacts.indexOf("soft and fluffy");

 Copy

This example returns -1 as this string does not exist in the array.

alligatorFacts.indexOf(80)

 Copy

This example returns 1.

alligatorFacts.indexOf(80, 2);

 Copy

This example returns -1 as the value does not exist past the index of 2.

Note: If you are not seeking the first result, you may wish to use lastIndexOf(). This method is similar to indexOf, but will find the first match starting at the last index of the array and working backward.

indexOf is helpful for use cases where you need a single index of a relevant search result.

Using find()

The find() method returns the first value in an array that matches the conditions of a function. If there is no match, the method returns undefined.

This is the basic syntax:

arr.find(callback(element[, index[, array]])[, thisArg])

 Copy

Let’s revisit the sample array of alligator facts:

const alligatorFacts = ["thick scales", 80, "4 foot tail", "rounded snout"];

 Copy

Then use find() to return the first value that has a length less than 13 characters:

alligatorFacts.find(el => el.length < 13);

 Copy

This example only uses the callback parameter.

80 is a numeric value. "rounded snout" is 13 characters long. "thick scales" is 12 characters long and "4 foot tail" is 11 characters long – both satisfy the conditions of the function. However, find() will only return the first value, so "thick scales" will be returned.

Here is an example also using the optional index parameter:

alligatorFacts.find((el, idx) => typeof el === "string" && idx === 2);

 Copy

"thick scales""4 foot tail", and "rounded snout" meet the first condition (typeof el === 'string'). If this was the only condition, it would return the first one, "thick scales". But the second condition (idx === 2) will cause this code to return "4 foot tall".

Note: If you are seeking the index instead of the value, you may wish to use findIndex(). This method also receives a function, but it returns the matching element’s index instead of the element itself.

find() is helpful for use cases where you want a single search result value.

Using filter()

The filter() method returns a new array of all the values in an array that matches the conditions of a function. If there is no match, the method returns an empty array.

This is the basic syntax:

let newArray = arr.filter(callback(currentValue[, index[, array]]) {
  // return element for newArray, if true
}[, thisArg]);

 Copy

Let’s revisit the sample array of alligator facts:

const alligatorFacts = ["thick scales", 80, "4 foot tail", "rounded snout", 80];

 Copy

Then use filter() to return all the values equal to 80:

alligatorFacts.filter(el => el === 80);

 Copy

The two 80 values in the array meet this condition. This code would return a new array: [80, 80].

filter() is helpful for use cases where you want multiple search result values.

Conclusion

In this article, you learned about Array.includes()Array.indexOfArray.find(), and Array.filter. Each can provide a solution to the needs of your use case.

  • Do you need to know only if it exists?
    • Use includes().
  • Do you need to get the element itself?
    • Use find() for a single item or filter() for multiple items.
  • Do you need to find the index of the element?
    • Use indexOf() to search for a primitive or findIndex() to search with a function.

Leave a Reply

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