JavaScript - findLast() method

revision:


Category : array

The findLast() method iterates the array in reverse order and returns the value of the first element that satisfies the provided testing function. If no elements satisfy the testing function, "undefined" is returned.

If you need to find:

The first element that matches, use find().
The index of the last matching element in the array, use findLastIndex().
The index of a value, use indexOf(). (It's similar to findIndex(), but checks each element for equality with the value instead of using a testing function.)
Whether a value exists in an array, use includes(). Again, it checks each element for equality with the value instead of using a testing function.
If any element satisfies the provided testing function, use some().

Syntax :

        findLast(callbackFn)
        findLast(callbackFn, thisArg)
    

Parameters:

callbackFn : a function to execute for each element in the array. It should return a truthy value to indicate a matching element has been found, and a falsy value otherwise. The function is called with the following arguments:

element : the current element being processed in the array.
index : the index of the current element being processed in the array.
array : the array findLast() was called upon.

thisArg : optional. A value to use as "this" when executing callbackFn.

Examples:

            const array1 = [5, 12, 50, 130, 44];
            const found = array1.findLast((element) => element > 45);
            console.log(found);
            // Expected output: 130
        

Practical examples

example: find the last element in an array matching on element properties.

code:
                    <div>
                        <p id="find-1"></p>
                    </div>
                    <script>
                        const inventory = [
                            { name: "apples", quantity: 2 },
                            { name: "bananas", quantity: 0 },
                            { name: "fish", quantity: 1 },
                            { name: "cherries", quantity: 5 },
                        ];
                        // return true inventory stock is low
                        function isNotEnough(item) {
                            return item.quantity < 2;
                        }
                        console.log(inventory.findLast(isNotEnough));
                        // { name: "fish", quantity: 1 }
                        document.getElementById("find-1").innerHTML = JSON.stringify(inventory.findLast(isNotEnough));
                    </script>
                

example: find last prime number in an array.

code:
                    <div>
                        <p id="find-2"></p>
                        <p id="find-3"></p>
                        <p id="find-4"></p>
                    </div>
                    <script>
                        function isPrime(element) {
                            if (element % 2 === 0 || element < 2) {
                                return false;
                        }
                        for (let factor = 3; factor <= Math.sqrt(element); factor += 2) {
                            if (element % factor === 0) {
                                return false;
                            }
                        }
                        return true;
                        }
                        console.log([4, 6, 8, 12].findLast(isPrime)); // undefined, not found
                        console.log([4, 5, 7, 8, 9, 11, 12].findLast(isPrime)); // 11
                        document.getElementById("find-2").innerHTML = "last Prime in the array? " + [4, 6, 8, 12].findLast(isPrime);
                        document.getElementById("find-3").innerHTML = "last Prime in the array? " + [4, 5, 7, 8, 9, 11, 12].findLast(isPrime);
            
                    </script>
                

example: return the lement that matches; else, undefined.

code:
                    <div>
                        <p id="find-5"></p>
                        <p id="find-6"></p>
                        <p id="find-7"></p>
                    </div>
                    <script>
                        const array = [{v: 1}, {v: 2}, {v: 3}, {v: 4}, {v: 5}];
                        console.log(array.findLast(elem => elem.v > 3));
                        document.getElementById("find-5").innerHTML = JSON.stringify(array.findLast(elem => elem.v > 3)); // {v: 5}
                        console.log(array.findLastIndex(elem => elem.v > 3)); // 4
                        document.getElementById("find-6").innerHTML = JSON.stringify(array.findLastIndex(elem => elem.v > 3)); // 4
                        
                    </script>
                

example: find the value of a visited element in an array.

code:
                    <div>
                        <p id="find-8"></p>
                        <p id="find-9"></p>
                        <p id="find-10"></p>
                        <p id="find-11"></p>
                    </div>
                    <script>
                        const array1 = [0, 1, , , , 5, 6];
                        document.getElementById("find-8").innerHTML = "original array : " + array1
                        array1.findLast((value, index) => {
                            console.log(`Visited index ${index} with value ${value}`);
                            document.getElementById("find-9").innerHTML += `Visited index ${index} with value ${value}` + "<br>";
                        });
                        array1.findLast((value, index) => {
                            if (index === 6) {
                            console.log(`Deleting array[5] with value ${array[5]}`);
                            document.getElementById("find-10").innerHTML = `Deleting array[5] with value ${array[5]}`
                            delete array[5];
                        }
                        console.log(`Visited index ${index} with value ${value}`);
                        document.getElementById("find-11").innerHTML += `Visited index ${index} with value ${value}` + "<br>";
                        });
            
                    </script>