Tutorial

Four Methods to Search Through Arrays in JavaScript

Updated on December 15, 2021
author

Stephen Hartfield

English
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.indexOf, Array.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]);

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];

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

alligatorFacts.includes("thick scales");

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);

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

alligatorFacts.includes(80);

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

alligatorFacts.includes('80');

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])

Let’s revisit the sample array of alligator facts:

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

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

alligatorFacts.indexOf("rounded snout");

The index of the string "rounded snout" - 3 - will be returned.

alligatorFacts.indexOf("soft and fluffy");

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

alligatorFacts.indexOf(80)

This example returns 1.

alligatorFacts.indexOf(80, 2);

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])

Let’s revisit the sample array of alligator facts:

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

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

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

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);

"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]);

Let’s revisit the sample array of alligator facts:

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

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

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

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.indexOf, Array.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.

Continue your JavaScript learning with iteration methods, accessor methods, and mutator methods.

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products


About the authors
Default avatar
Stephen Hartfield

author

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
1 Comments


This textbox defaults to using Markdown to format your answer.

You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!

On Line,

alligatorFacts.indexOf(80, 2);

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

This Will Result 4. Because in const alligatorFacts = [“thick scales”, 80, “4 foot tail”, “rounded snout”, 80]; Number 80 is two times present.

Try DigitalOcean for free

Click below to sign up and get $200 of credit to try our products over 60 days!

Sign up

Join the Tech Talk
Success! Thank you! Please check your email for further details.

Please complete your information!

Featured on Community

Get our biweekly newsletter

Sign up for Infrastructure as a Newsletter.

Hollie's Hub for Good

Working on improving health and education, reducing inequality, and spurring economic growth? We'd like to help.

Become a contributor

Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

Welcome to the developer cloud

DigitalOcean makes it simple to launch in the cloud and scale up as you grow — whether you're running one virtual machine or ten thousand.

Learn more
DigitalOcean Cloud Control Panel