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.