Personally, I wouldn't choose either solution. Here is why:

LastIndexOf:

The problem lies in the comparing of elements while searching through the array. It does compare the elements using strict equality. Therefore comparing objects will always fail, except they are the same. In OP case they are different.

Slice & reverse one-liner @adeneo

Given an array of three elements [{key: A},{key: B},{key: C}] and the lookup for the last index of key = D will give you an index of 3. This is wrong as the last index should be -1 (Not found)

Looping through the array

While this is not necessarily wrong, looping through the whole array to find the element isn't the most concise way to do it. It's efficient yes, but readability can suffer from it. If I had to choose one, I'd probably choose this one. If readability / simplicity is your friend, then below is yet one more solution.


A simple solution

We can make lastIndexOf work, we just need to make the value comparable (strict equality conform). Or simply put: we need to map the objects to a single property that we want to find the last index of using javascript's native implementation.

const arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

arr.map(el => el.key).lastIndexOf("e"); //4
arr.map(el => el.key).lastIndexOf("d"); //-1

// Better:
const arrKeys = arr.map(el => el.key);
arrKeys.lastIndexOf("c"); //2
arrKeys.lastIndexOf("b"); //1

A fast solution

Simple backwards lookup (as concise and as fast as possible). Note the -1 return instead of null/undefined.

const arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

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

lastIndexOf(arr, "e"); //4
lastIndexOf(arr, "x"); //-1
Answer from Tom Siwik on Stack Overflow
Top answer
1 of 7
19

Personally, I wouldn't choose either solution. Here is why:

LastIndexOf:

The problem lies in the comparing of elements while searching through the array. It does compare the elements using strict equality. Therefore comparing objects will always fail, except they are the same. In OP case they are different.

Slice & reverse one-liner @adeneo

Given an array of three elements [{key: A},{key: B},{key: C}] and the lookup for the last index of key = D will give you an index of 3. This is wrong as the last index should be -1 (Not found)

Looping through the array

While this is not necessarily wrong, looping through the whole array to find the element isn't the most concise way to do it. It's efficient yes, but readability can suffer from it. If I had to choose one, I'd probably choose this one. If readability / simplicity is your friend, then below is yet one more solution.


A simple solution

We can make lastIndexOf work, we just need to make the value comparable (strict equality conform). Or simply put: we need to map the objects to a single property that we want to find the last index of using javascript's native implementation.

const arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

arr.map(el => el.key).lastIndexOf("e"); //4
arr.map(el => el.key).lastIndexOf("d"); //-1

// Better:
const arrKeys = arr.map(el => el.key);
arrKeys.lastIndexOf("c"); //2
arrKeys.lastIndexOf("b"); //1

A fast solution

Simple backwards lookup (as concise and as fast as possible). Note the -1 return instead of null/undefined.

const arr = [ { key: "a" }, { key: "b" }, { key: "c" }, { key: "e" }, { key: "e" }, { key: "f" } ];

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

lastIndexOf(arr, "e"); //4
lastIndexOf(arr, "x"); //-1
2 of 7
4

With ES2015 and findIndex you can pass a callback to look for an objects key.

If you make a copy of the array, and reverse it, you can find the last one by subtracting that index from the total length (and 1, as arrays are zero based)

It's not very efficient, but it's one line, and works well for normally sized arrays i.e. not a million indices

var idx = arr.length - 1 - arr.slice().reverse().findIndex( (o) => o.key == 'key' );

Show code snippet

var arr = [{key : 'not'}, {key : 'not'}, {key : 'key'}, {key : 'not'}];

var idx = arr.length - 1 - arr.slice().reverse().findIndex( (o) => o.key == 'key' ); // 2

console.log(idx)
Run code snippetEdit code snippet Hide Results Copy to answer Expand

A more efficient approach would be to iterate backwards until you find the object you're looking for, and break the loop

var arr = [{key: 'not'}, {key: 'not'}, {key: 'key'}, {key: 'not'}];

var idx = (function(key, i) {
  for (i; i--;) {
    if (Object.values(arr[i]).indexOf(key) !== -1) {
      return i;
      break;
    }
  }   return -1;
})('key', arr.length);

console.log(idx)
Run code snippetEdit code snippet Hide Results Copy to answer Expand

🌐
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_array.asp
JavaScript Array lastIndexOf() Method
The lastIndexOf() method returns the last index (position) of a specified value.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › TypedArray › lastIndexOf
TypedArray.prototype.lastIndexOf() - JavaScript | MDN
The lastIndexOf() method of TypedArray instances returns the last index at which a given element can be found in the typed array, or -1 if it is not present. The typed array is searched backwards, starting at fromIndex.
🌐
Programiz
programiz.com › javascript › library › array › lastindexof
JavaScript Array lastIndexOf() (with Examples)
Here alphabets.lastIndexOf("a", -3) starts the search at third last position of the array and returns the last occurrence of 'a' which is 0.
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript array lastindexof method
JavaScript Array lastIndexOf Method
September 1, 2008 - Explore the lastIndexOf method in JavaScript for locating the last occurrence of elements in arrays with practical examples.
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.indexof()
JavaScript Array indexOf() Method
November 6, 2024 - Array.prototype.lastIndexOf() Length Property · Append an Element: push() Remove the Last element: pop() Prepend Elements: unshift() Remove the first Elements: shift() Manipulate Elements: splice() String.prototype.slice() Locate Elements: indexOf() Find an Element: find() Find an Index of an Element: findIndex() Check If an Element is in the Array: includes() Transform Array Elements: map() Filter Array Elements: filter() Reduce an Array Into a Value: reduce() Reduce an Array Into a Value: reduceRight() Check If Every Element Passes a Test: every() Check If At Least One Element Passes a Test: some() Iterate Array Elements: forEach() Sort Array Elements: sort() Merge Arrays: concat() Create an Array from an Iterable: from() Create an Aray: Array.of() Flatten an Array: flat() Flatten & Map Elements: flatMap() Concatenate Array Elements Into a String: join() Array Destructuring ·
🌐
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.
Find elsewhere
🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › lastIndexOf
JavaScript Array lastIndexOf() - Find Last Index of Element | Vultr Docs
November 29, 2024 - Note that lastIndexOf() does not work directly on nested arrays or objects. Perform a search using lastIndexOf() with complex conditions such as nested arrays. ... const complexArray = [[1, 2], [3, 4], [1, 2]]; const target = JSON.stringify([1, ...
🌐
Javatpoint
javatpoint.com › javascript-array-lastindexof-method
JavaScript Array lastIndexOf() Method
This method changes the length of the original array. Syntax The method is represented by the following syntax: array.
🌐
Codecademy
codecademy.com › docs › javascript › arrays › .lastindexof()
JavaScript | Arrays | .lastIndexOf() | Codecademy
July 13, 2023 - The .lastIndexOf() array method returns the last index at which an element can be found.
🌐
GitHub
github.com › mdn › content › blob › main › files › en-us › web › javascript › reference › global_objects › array › lastindexof › index.md
content/files/en-us/web/javascript/reference/global_objects/array/lastindexof/index.md at main · mdn/content
The `lastIndexOf()` method is [generic](/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#generic_array_methods). It only expects the `this` value to have a `length` property and integer-keyed properties. ... The following example uses `lastIndexOf()` to locate values in an array. ... You cannot use `lastIndexOf()` to search for `NaN`. ... You cannot use `lastIndexOf()` to search for empty slots in sparse arrays. ... The `lastIndexOf()` method reads the `length` property of `this` and then accesses each property whose key is a nonnegative integer less than `length`.
Author   mdn
🌐
Microsoft Learn
learn.microsoft.com › en-us › dotnet › api › system.array.lastindexof
Array.LastIndexOf Method (System) | Microsoft Learn
Searches for the specified object and returns the index of the last occurrence within the entire one-dimensional Array. public: static int LastIndexOf(Array ^ array, System::Object ^ value);
🌐
TutorialsPoint
tutorialspoint.com › typescript › typescript_array_lastindexof.htm
TypeScript - Array lastIndexOf()
array.lastIndexOf(searchElement[, fromIndex]); searchElement − Element to locate in the array. fromIndex − The index at which to start searching backwards. Defaults to the array's length, i.e., the whole array will be searched. If the index is greater than or equal to the length of the ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › findLastIndex
Array.prototype.findLastIndex() - JavaScript | MDN
The findLastIndex() method of Array instances iterates the array in reverse order and returns the index of the first element that satisfies the provided testing function. If no elements satisfy the testing function, -1 is returned.
🌐
ZetCode
zetcode.com › js-array › lastindexof
JavaScript lastIndexOf - finding elements in arrays and strings
We demonstrate how lastIndexOf works with objects. It only finds objects that reference the exact same object in memory. Even though obj1 and obj3 have the same content, they are different objects.
🌐
W3Schools
w3schools.com › java › ref_arraylist_lastindexof.asp
Java ArrayList lastIndexOf() Method
import java.util.ArrayList; public ...("Ford")); } } Try it Yourself » · The lastIndexOf() method returns the position of the last occurrence of a value in the list....
🌐
GeeksforGeeks
geeksforgeeks.org › typescript › typescript-array-lastindexof-method
TypeScript Array lastIndexOf() Method - GeeksforGeeks
July 19, 2024 - The Array.prototype.lastIndexOf() method in TypeScript is used to find the last index at which a given element can be found in the array, searching backwards from the fromIndex. It returns the index of the found element, or -1 if the element ...