The syntax for the lastIndexOf is:

string.lastIndexOf(searchValue[, fromIndex])

where fromIndex is optional and represents the index from which to start looking. However, the search is performed backwards, so starting from position 3 in your example would be searching through string "This";

Answer from ZenMaster on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › String › lastIndexOf
String.prototype.lastIndexOf() - JavaScript | MDN
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.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › lastIndexOf
Array.prototype.lastIndexOf() - JavaScript | MDN
The lastIndexOf() method of Array instances 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.
🌐
W3Schools
w3schools.com › jsref › jsref_lastindexof.asp
JavaScript String lastIndexOf() Method
The lastIndexOf() method returns the index from the beginning (position 0).
🌐
Programiz
programiz.com › javascript › library › string › lastindexof
JavaScript String lastIndexOf() (With Examples)
In the above example, we have passed fromIndex as a second parameter. So, the lastIndexOf() method searches the substring backward from fromIndex.
🌐
W3Schools
w3schools.com › jsref › jsref_lastindexof_array.asp
JavaScript Array lastIndexOf() Method
The lastIndexOf() starts at a specified index and searches from right to left (from the given postion to the beginning of the array).
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript string methods › string.prototype.lastindexof()
JavaScript String lastIndexOf() Method
November 3, 2024 - To find the index of the first occurrence of a substring within a string, you use the lastindexOf() method.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript-string-lastindexof-method
JavaScript String lastIndexOf() Method | GeeksforGeeks
July 16, 2024 - // JavaScript to illustrate lastIndexOf() method function func() { // Original string let str = 'Departed Train'; // Finding index of occurrence of 'train' let index = str.lastIndexOf('train'); console.log(index); } func();
Find elsewhere
Top answer
1 of 1
4

You're misinterpreting .indexOf(). indexOf returns the first index at which a given element can be found in the array, or -1 if it is not present. So index would be the index of the counter in counters. In short, you're comparing an object (counter) to a number (index).

That said, it also depends on how you're searching for the object in the array. If trying to find an object which matches a certain key/value structure, .indexOf won't work for the reason you mentioned. As pointed out by Gabriele, if searching using a reference, it will work.

If using a reference isn't an option, as an alternative you could use .findIndex(), or .map(), and find the object based on one of its properties, like id.

const counters = [{id: 1, value: 0}, {id: 2, value: 0}, {id: 3, value: 0}, {id: 4, value: 0}];

const findBySameness = {id: 3, value: 0};
const findByRef = counters[2];

const indexBySameness = counters.indexOf(findBySameness);
console.log('Index by sameness: ', indexBySameness); // Do not find the object index
const indexByRef = counters.indexOf(findByRef);
console.log('Index by reference: ', indexByRef); // Found the object index

// If a reference to the object is not available you can use the following methods

// With .findIndex
const index3 = counters.findIndex(item => item.id === findBySameness.id)
console.log('Index: ', index3); // Found the object index

// With .map
const index2 = counters.map(item => item.id).indexOf(findBySameness.id);
console.log('Index: ', index2); // Found the object index

Top answer
1 of 5
1

There are many ways to achieve it.

All depends on Your "creativity".


I'll write 3 of them:

1) Straight looping until last match:

const lastIndexOf = (haystack, needle) => {
  let index = -1;
  haystack.forEach(function(element, i) {
    if (element === needle) index = i;
  });
  return index;
}


let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']

console.log('Index of:', fruits.indexOf('mango')); 
console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
console.log('Last Index of:', lastIndexOf(fruits, 'potato'));

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

2) Looping using -1 step and stopping at first match:

const lastIndexOf = (haystack, needle) => {
  for (let i = haystack.length -1; i >= 0; i--) {
    if (haystack[i] === needle) return i;
  }
  return -1;
}


let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']

console.log('Index of:', fruits.indexOf('mango')); 
console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
console.log('Last Index of:', lastIndexOf(fruits, 'potato'));

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);

3) Reverse sorting + "length math":

const lastIndexOf = (haystack, needle) => {
  const rIndex = haystack.reverse().indexOf(needle);
  return (rIndex > -1) ? haystack.length - rIndex - 1 : -1;
}


let fruits = ['apple', 'mango', 'pear', 'strawberry', 'bananas', 'mango', 'cherry']

console.log('Index of:', fruits.indexOf('mango')); 
console.log('Last Index of:', lastIndexOf(fruits, 'mango'));
console.log('Last Index of:', lastIndexOf(fruits, 'potato'));

console.log(lastIndexOf([ 0, 1, 4, 1, 2 ], 1), "=?", 3);


P.S. In case of very big arrays these 3 methods can be less optimal, since You cannot predict the value You're looking for is near to end or beginning of array.

So for such cases You can inspire from binary tree algorithm.

Everything depends on complexity of task.

2 of 5
1

Just go from the last element and return if you find what you are looking for.

Last index would be array.length - 1. Use classic for loop.

Good luck in your study!

🌐
O'Reilly
oreilly.com › library › view › javascript-the-definitive › 0596101996 › re167.html
JavaScript: The Definitive Guide, 5th Edition
August 17, 2006 - String.lastIndexOf( ): search a string backward — ECMAScript v1 · The substring to be searched for within string
Author   David Flanagan
Published   2006
Pages   1018
🌐
TutorialsPoint
tutorialspoint.com › javascript › string_lastindexof.htm
JavaScript String lastIndexOf() Method
This method accepts an optional parameter named position, which specifies the position in the original string from where the method starts searching for the specified substring. The default value of this parameter is 0. For example, "hello".lastIndexOf("l", 2) returns 2, while "hello".lastIndexOf("l", 3) returns 3.
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › lastIndexOf
JavaScript Array lastIndexOf() - Find Last Index of Element | Vultr Docs
November 29, 2024 - The lastIndexOf() method in JavaScript is a robust and versatile tool for locating the last index of an element in an array. With the ability to specify a starting index and differentiate between elements in varied orders, it effectively addresses ...
🌐
The Valley of Code
thevalleyofcode.com › javascript-string-lastindexof
The String lastIndexOf() method
'JavaScript is a great language. Yes I mean JavaScript'.lastIndexOf('Script') //47 'JavaScript'.lastIndexOf('C++') //-1
🌐
Programiz
programiz.com › javascript › library › array › lastindexof
JavaScript Array lastIndexOf() (with Examples)
In the above example, we have used the lastIndexOf() method to find the index of the last occurrence of 'a' and 'e'.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-array-lastindexof-method
JavaScript Array lastIndexOf() Method - GeeksforGeeks
July 15, 2024 - The JavaScript Array lastIndexOf() Method is used to find the index of the last occurrence of the search element provided as the argument to the function.
🌐
Javatpoint
javatpoint.com › javascript-string-lastindexof-method
JavaScript String lastIndexOf() Method - javatpoint
lastIndexOf() map() of() pop() push() reverse() reduce(function, initial) reduceRight() some() shift() slice() sort() splice() toLocaleString() toString() unshift() values() exec() test() toString() Python · Java · Javascript · HTML · Database · PHP · C++ React ·