findLast

2 snippets in JavaScript

JSJavaScript

find() and findIndex()

JS · Arrays
Syntax
arr.find(callback)
arr.findIndex(callback)
arr.findLast(callback)
arr.findLastIndex(callback)
Example
const users = [
  { id: 1, name: "Ava" },
  { id: 2, name: "Bo" },
  { id: 3, name: "Ava" },
];
console.log(users.find(u => u.name === "Ava"));     // { id: 1, name: "Ava" }
console.log(users.findLast(u => u.name === "Ava")); // { id: 3, name: "Ava" }
console.log(users.findIndex(u => u.id === 2));       // 1

Note find() returns the first match or undefined. findLast() (ES2023) searches from the end. Both return the element, not a boolean.

findLast() and findLastIndex()

JS · Modern Features
Syntax
arr.findLast(callback)
arr.findLastIndex(callback)
Example
const transactions = [
  { type: "credit", amount: 500 },
  { type: "debit", amount: 200 },
  { type: "credit", amount: 300 },
  { type: "debit", amount: 150 },
];

const lastCredit = transactions.findLast(t => t.type === "credit");
console.log(lastCredit); // { type: "credit", amount: 300 }

const lastCreditIdx = transactions.findLastIndex(t => t.type === "credit");
console.log(lastCreditIdx); // 2

Note ES2023. Searches from the end of the array. More readable and efficient than reversing first or using a manual reverse loop.

Frequently asked questions

How does JavaScript handle findLast?
JavaScript covers this with 2 copy-ready snippets on this page. The "find() and findIndex()" snippet in JavaScript uses `arr.find(callback)`.
Which code does the JavaScript example use?
The "find() and findIndex()" snippet uses `arr.find(callback)`, from the Arrays section of the JavaScript cheat sheet.
What other JavaScript snippets are shown for "findLast"?
Besides "find() and findIndex()", this page also shows "findLast() and findLastIndex()".
Is there anything to watch out for?
Yes. For "find() and findIndex()": find() returns the first match or undefined. findLast() (ES2023) searches from the end. Both return the element, not a boolean.