JavaScript - lastIndexOf() method

revision:


Category : array

The lastIndexOf() method returns the last index at which a given element can be found in the array, or -1 if it is not present. The array is searched backwards, starting at fromIndex.

Syntax :

        lastIndexOf(searchElement)
        lastIndexOf(searchElement, fromIndex)
    

Parameters:

searchElement : element to locate in the array.

fromIndex : optional. Zero-based index at which to start searching backwards, converted to an integer.

Negative index counts back from the end of the array — if "fromIndex < 0", "fromIndex + array.length" is used.
If "fromIndex < -array.length", the array is not searched and -1 is returned. You can think of it conceptually as starting at a nonexistent position before the beginning of the array and going backwards from there. There are no array elements on the way, so searchElement is never found.
If "fromIndex >= array.length" or "fromIndex is omitted", "array.length - 1" is used, causing the entire array to be searched. You can think of it conceptually as starting at a nonexistent position beyond the end of the array and going backwards from there. It eventually reaches the real end position of the array, at which point it starts searching backwards through the actual array elements.

Examples:

            const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
            console.log(animals.lastIndexOf('Dodo'));
            // Expected output: 3
            console.log(animals.lastIndexOf('Tiger'));
            // Expected output: 1
        

Category : string

The lastIndexOf() method of String values searches this string and returns the index of the last occurrence of the specified substring. It takes an optional starting position and returns the last occurrence of the specified substring at an index less than or equal to the specified number.

The lastIndexOf() method searches the string from the end to the beginning. It returns the index from the beginning (position 0) and returns -1 if the value is not found.

The lastIndexOf() method is case-sensitive.

Syntax :

        string.lastIndexOf(searchString)
        lastIndexOf(searchString, position)
    

Parameters:

searchString : required. Substring to search for. All values are coerced to strings, so omitting it or passing undefined causes indexOf() to search for the string "undefined", which is rarely what you want.

position : optional. The method returns the index of the last occurrence of the specified substring at a position less than or equal to position, which defaults to +Infinity. If position is greater than the length of the calling string, the method searches the entire string. If position is less than 0, the behavior is the same as for 0 — that is, the method looks for the specified substring only at index 0.

Examples :

        const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
        const searchTerm = 'dog';
        console.log(`The index of the first "${searchTerm}" from the end is ${paragraph.lastIndexOf(searchTerm)}`);
        // Expected output: "The index of the first "dog" from the end is 52"

        'hello world hello'.lastIndexOf('world', 4) returns -1 — because, while the substring world does occurs at index 6, that position is not less than or equal to 4.
        'hello world hello'.lastIndexOf('hello', 99) returns 12 — because the last occurrence of hello at a position less than or equal to 99 is at position 12.
        'hello world hello'.lastIndexOf('hello', 0) and 'hello world hello'.lastIndexOf('hello', -5) both return 0 — because both cause the method to only look for hello at index 0.
    

Practical examples

example: using lastIndexOf() method.

code:
                    <div>
                        <p id="index-1"></p>
                        <p id="index-2"></p>
                        <p id="index-3"></p>
                        <p id="index-4"></p>
                        <p id="index-5"></p>
                        <p id="index-6"></p>
                        <p id="index-7"></p>
                    </div>
                    <script>
                        const numbers = [2, 5, 9, 2];
                        console.log(numbers.lastIndexOf(2)); // 3
                        console.log(numbers.lastIndexOf(7)); // -1
                        console.log(numbers.lastIndexOf(2, 3)); // 3
                        console.log(numbers.lastIndexOf(2, 2)); // 0
                        console.log(numbers.lastIndexOf(2, -2)); // 0
                        console.log(numbers.lastIndexOf(2, -1)); // 3
                        document.getElementById("index-1").innerText = " array.lastindexOf() : " + numbers;
                        document.getElementById("index-2").innerText = " lastindexOf(2) : " + numbers.lastIndexOf(2);
                        document.getElementById("index-3").innerText = " lastindexOf(7) : " + numbers.lastIndexOf(7);
                        document.getElementById("index-4").innerText = " lastindexOf(2, 3) : " + numbers.lastIndexOf(2, 3);
                        document.getElementById("index-5").innerText = " lastindexOf(2, 2) : " + numbers.lastIndexOf(2, 2);
                        document.getElementById("index-6").innerText = " lastindexOf(2, -2) : " + numbers.lastIndexOf(2, -2);
                        document.getElementById("index-7").innerText = " lastindexOf(2, -1) : " + numbers.lastIndexOf(2, -1);
                    </script>
                

example: finding all the occurences of an element.

code:
                    <div>
                        <p id="index-8"></p>
                        <p id="index-9"></p>
                        <p id="index-10"></p>
                        <p id="index-11"></p>
                    </div>
                    <script>
                            const indices = [];
                            const array = ["a", "b", "a", "c", "a", "d"];
                            const element = "a";
                            let idx = array.lastIndexOf(element);
                            while (idx !== -1) {
                                indices.push(idx);
                                idx = idx > 0 ? array.lastIndexOf(element, idx - 1) : -1;
                            }
                            console.log(indices);
                            // [4, 2, 0]
                            document.getElementById("index-8").innerHTML = "indices of element 'a': " + JSON.stringify(indices);
                    </script>
                

example: search for the last occurence of "planet".

lastIndexOf() returns the index of the last occurrence of a specified value in a string.

Find the last occurence of "planet" :

Find the last occurence of "Planet" :

Find the last occurence of "Planet", starting at position 20 :

code:
                    <div>
                        <p>lastIndexOf() returns the index of the last occurrence of a specified value in a string.</p>
                        <p id="index-12"></p>
                        <p>Find the last occurence of "planet" : <span id="index-13"></span></p>
                        <p>Find the last occurence of "Planet" : <span id="index-14"></span></p>
                        <p>Find the last occurence of "Planet", starting at position 20 : <span id="index-15"></span></p>
                    </div>
                    <script>
                        let text = "Hello planet earth, you are a great planet.";
                        document.getElementById("index-12").innerHTML = "sentence : " + text;
                        let result = text.lastIndexOf("planet");
                        document.getElementById("index-13").innerHTML = result;
                        let result2 = text.lastIndexOf("Planet");
                        document.getElementById("index-14").innerHTML = result2;
                        let result3 = text.lastIndexOf("planet", 20);
                        document.getElementById("index-15").innerHTML = result3;
                    </script>