Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

javascript

What is the lastIndexOf method in JavaScript Arrays?

Khizar Hayat Saani

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

lastIndexOf() is a built-in method that we can use with the Array type in JavaScript.

The following is the method prototype:

Array.lastIndexOf(searchElement, fromIndex)

Functionality

We use the lastIndexOf() method to find the position of an element in an array.

The method is similar to the indexOf() method, except that lastIndexOf() starts searching from the end of the array (unless otherwise specified) and moves backward.

The lastIndexOf() method

Parameters and return

The method takes the following input parameters:

  • searchElement: The element to to be searched within the array.

  • fromIndex: The index where the search will start. This is an optional parameter. If not otherwise specified, the search starts from the end of the array.

The lastIndexOf method returns the index of the last occurrence of the searchElement.

If the element is not found, the method returns -1.

Code

// defining an array
var numbers = [12, 8, 2, 5, 12, 1, 20];
// lastIndexOf() returns the last occurance
var index1 = numbers.lastIndexOf(5);
console.log(index1); // 3
var index2 = numbers.lastIndexOf(12);
console.log(index2); // 4
// specifying starting index of search
var index3 = numbers.lastIndexOf(12, 3);
console.log(index3); // 0
// lastIndexOf returns -1 if not found
var index4 = numbers.lastIndexOf(33);
console.log(index4); // -1

RELATED TAGS

javascript

CONTRIBUTOR

Khizar Hayat Saani
Copyright ©2022 Educative, Inc. All rights reserved

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring