JavaScript - find() method

revision:


Category : array

The find() method returns the value of the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, "undefined" is returned.

If you need the "index of the found element" in the array, use findIndex().
If you need to find "the index of a value", use Array.prototype.indexOf(). (It's similar to findIndex(), but checks each element for equality with the value instead of using a testing function.).
If you need to find "if a value exists in an array, use Array.prototype.includes(). It checks each element for equality with the value instead of using a testing function.
If you need to find "if any element satisfies the provided testing function, use Array.prototype.some().

The find() method does not execute the function for empty elements and does not change the original array.

Differences with the Array.filter() method:

The function and syntax of find() is very much like the Array.filter method, except it only returns a single element.
When nothing is found, the find() method returns a value of undefined.

So, if you only need a single value, use the find() method! When you need to find/return multiple values, reach for the filter() method instead.

Syntax :

        array.find(function(currentValue, index, arr),thisValue)
        array.find(callbackFn)
        array.find(callbackFn, thisArg)
    

Parameter values:

function, callbackFn: required; a function to run for each array element.This is a function to execute on each value in the array, taking 3 arguments:

1/ currentValue, element: required; the value of the current element; the current element being processed in the array.
2/ index: optional; the index (position) of the current element in the array being processed; 3/
arr: optional; the array of the current element; the array "find()"" was called upon.

thisValue, thisArg: optional; default "undefined"; a value passed to the function as its "this" value, i.e the value of the first element in the array that satisfies the provided testing function.

Syntax examples

        // Arrow function
        find((element) => { ... } )
        find((element, index) => { ... } )
        find((element, index, array) => { ... } )
        
        // Callback function
        find(callbackFn)
        find(callbackFn, thisArg)
        
        // Inline callback function
        find(function(element) { ... })
        find(function(element, index) { ... })
        find(function(element, index, array){ ... })
        find(function(element, index, array) { ... }, thisArg)
    

Examples :

        const array1 = [5, 12, 8, 130, 44];
        const found = array1.find(element => element > 10);
        console.log(found);
        // Expected output: 12
    

Practical Examples

example: find() method

code:

                    <div>
                        <p class="spec" id="one"></p>
                        <p class="spec" id="two"></p>
                    </div>
                    <script>
                        const array1 = [5, 12, 8, 130, 44];
                        const found = array1.find(element => element > 10);
                        document.getElementById("one").innerHTML = "array: " + array1;
                        document.getElementById("two").innerHTML = "first element greater than 10: " + found;
                    </script>
                

example: input and find() method

code:

                    <div>
                        <p class="spec" ><input type="number" id="ageToCheck" value="18"></p>
                        <button style="margin-left: 2vw;" onclick="findIt()">Try it</button>
                        <p class="spec" id="three_A"></p>
                    </div>
                    <script>
                        const ages = [4, 12, 16, 20];
                        function checkAge(age) {
                            return age > document.getElementById("ageToCheck").value;
                        }
                        function findIt() {
                        document.getElementById("three_A").innerHTML = ages.find(checkAge);
                        }
                    </script>
                

example: find designated plants in an array

code:

                    <div>
                        <p class="spec"  id="four"></p>
                        <p class="spec"  id="five"></p>
                    </div>
                    <script>
                        const deciduous = [
                            { name: "birch", count: 4 },
                            { name: "maple", count: 5 },
                            { name: "oak", count: 2 }
                            ];
                        const evergreens = [
                            { name: "cedar", count: 2 },
                            { name: "fir", count: 6 },
                            { name: "pine", count: 3 }
                            ];
                        const hasFiveOrMore = el => el.count >= 5;
            
                        const decResult = deciduous.find(hasFiveOrMore);
                            // { name: "maple", count: 5 }
            
                        const evgResult = evergreens.find(hasFiveOrMore);
                            // { name: "fir", count: 6 }
                        document.getElementById("four").innerHTML = JSON.stringify(decResult);                      
                        document.getElementById("five").innerHTML = JSON.stringify(evgResult);                              
                    </script>
                

example: find the value of the first element with a value over 18.

code:
                    <div>
                        <p class="spec" id="six"></p>
                        <p class="spec" id="seven"></p>
                    </div>
                    <script>
                        const ages1 = [3, 10, 18, 20];
                        document.getElementById("six").innerHTML = "first age over 18 : " + ages1.find(checkAge);
                        function checkAge(age) {
                            return age > 18;
                        }
                    </script>