If a program or a script works with different values ​​united by some formal feature, it is most appropriate to use arrays to store them. These are structures in JavaScript with unique names, and indexes used to address values within an array.

In addition, arrays also have a large number of special methods for working with their elements. They are always available out-of-the-box and allow you to change or correct the structure and contents of arrays with just one line.

Therefore, it is much easier to work with data (elements) in arrays, since with just one line of code you can replace, delete, or even create a selection of values ​​based on a formal attribute. For direct requests for indexes and array values, there are several methods, each with its own characteristics.

The find() method allows you to check for the presence of a certain value in an array, in cases when you do not know its index. At the same time, it accepts various conditions for search criteria, which makes it possible to use it, including with complex functions.

Syntax

The find() method must be specified in binding to an array, so it must be declared before the method initialization. If the required value is not found in the array during the search, the method will return undefined. The same answer will be received if you apply it to an empty (without values) array.

At runtime, the method reads all the elements of the array, even if their values ​​have been removed. When a search value is found in the array, it will be returned as it exists in the array. It is important to note that after finding the desired result, the method stops further reading.

This means that if there are several duplicate values ​​in the array that match the search parameter, the method will return only one (closest to the beginning of the array (index = 0) and will stop working.

The basic syntax of the find() method:

arrayName.find(functionName);

arrayName is the name of the array where the search will be performed

functionName is the name of the function where the search condition or value will be.

In total, the method can take 5 different parameters that can affect the search process, but only calling the function that (or where) the check will be performed is mandatory. The function type also affects the ability to use optional parameters.

Optional parameters:

elem - current array element

ind- index of the current array element (elem)

arrayName - the name of the array where it is searched for

thisArg- execution context ("this") to use inside the function

How to use the find() method

You can set the search condition (functionName) in three different ways.

Option 1. Callback function. The easiest way for beginners is using the Callback function. In this case, reading each element of the array, the method will perform a search based on the algorithm specified in the separated function.

Example:

let numbers = [63, 15, 92, 20, 44];
function CheckNum(num) {
  return num == 20;
}
console.log(numbers.find(CheckNum));

Result:

20

In this example, the output to the console is initialized on the last line. The method itself performs a check in the array of numbers and refers to the CheckNum function, which implements an algorithm for finding the array value that is equal to 20. From optional parameters, only thisArg can be used with callback functions:

arrayName.find(functionName, thisArg);

Option 2. Inline callback. Inline callback allows you to specify a function with a check directly in the body of the method. This optimises the code, but requires more attention to syntax and search terms.

Example:

let numbers = [63, 15, 92, 20, 44];
console.log(numbers.find(function (number) { return number == 20; }));

Result:

20

The result of execution will be identical to the code from Option 1, while taking up only 2 lines of code.find() with such a function can take parameters: elem, ind, arrayName and thisArg.

arrayName.find(function (elem, ind, arrayName) { }, thisArg);

Option 3. Arrow function. Arrow functions are more compact than inline callbacks, but have some restrictions on the variability of setting function conditions. In case with find() they are best for searches based on only one specific condition.

Example:

let numbers = [63, 15, 92, 20, 44];
console.log(numbers.filter((number) => number == 20));

Result:

[ 20 ]

Pay attention that the search result by arrow function will be returned as an array, while in other cases it will be the value of the array element. You can use with Arrow function all parameters except thisArg:

arrayName.find((elem, ind, arrayName) =>{ });

Test yourself

  • Task 1. In an array of numbers, use the find() method to find a number less than 10 using the three kinds of functions which this method supports. Print the results of their execution to the console.

let numbers = [25, 81, 14, 35, 4, 13];

Solution. This array has only one value less than ten, so it will be enough to execute each type of function once.

let  numbers = [25, 81, 14, 35, 4, 13];
function CheckNum(num) {
  return num < 10;
}
console.log(numbers.find(CheckNum));
console.log(numbers.find(function (number) { return number < 10; }));
console.log(numbers.filter((number) => number < 10));

Result:

4
4
[ 4 ]
  • Task 2. In the given array of words, find and display the names of the seasons in the console using the find() method. Use only inline functions.

let words = [winter, car, sky, spring, autumn, flower, bus, table];

Solution. There are only four seasons, so for each of them we will implement a find() call with the desired name of the season. Then we will place them inside the console.log() methods.

let words = ['winter', 'car', 'sky', 'spring', 'autumn', 'flower', 'bus', 'table'];
console.log(words.find(function (season) { return season == 'winter'; }));
console.log(words.find(function (season) { return season == 'spring'; }));
console.log(words.find(function (season) { return season == 'summer'; }));
console.log(words.find(function (season) { return season == 'autumn'; }));

Result:

winter
spring
undefined
autumn

Since there is no "summer" value in the word array, we got "undefined" instead.

  • Task 3. Using the find() method and arrow functions, find the elements (families) that have more than and less than 2 family members in the "families" array. Print the results of the search to the console.

let families = [
    {name: 'Johnsons', members: 2},
    {name: 'Robertsons', members: 4},
    {name: 'Stevensons', members: 2},
    {name: 'Jacobs', members: 1} ];

Solution. Each element of the array has two values (name and members), so it will be important to clarify in the arrow function condition that we will check only the members field values.

let families = [
    {name: 'Johnsons', members: 2},
    {name: 'Robertsons', members: 4},
    {name: 'Stevensons', members: 2},
    {name: 'Jacobs', members: 1} ];
  console.log(families.filter((number) => number.members > 2));
  console.log(families.filter((number) => number.members < 2));

Result:

[ { name: 'Robertsons', members: 4 } ]
[ { name: 'Jacobs', members: 1 } ]

FAQ

find() VS findIndex()

findIndex() works according to the same rules as find() but returns not the value, but only its index in the array.

find() VS lastIndexOf()

lastIndexOf() returns the index of the value closest to the end of the array. Unlike find(), it does not stop reading an array if it finds a value that is repeated multiple times in the array.

find() VS some()

some() returns true if at least one element of the array matches the test condition specified in the function. If there are no such elements, it returns false.

find() VS filter()

find() stops reading an array after finding a matching value, even if there are the identical values in the array. The filter() method displays the values of all array elements whose values match the condition.