Skip to main content Accessibility Feedback

How to find the last matching item in an array with the new Array.prototype.findLast() method in JavaScript

This week, we’re looking at new Array methods in the latest version of JavaScript, ES2023.

So far, we’ve learned how to create new arrays while mutating them with the toReversed() method, the toSpliced() method, and the with() method.

Today, we’re going to switch things up and look at how to find the last matching up with the Array.prototype.findLast() method.

Let’s dig in!

Finding an item in JavaScript

Finding items in array has gotten increasingly easy over the years. Most recently, the Array.prototype.filter() method can be used to find all of the items in an array that match some criteria, while the Array.prototype.find() method finds the first matching item.

For example, imagine you have an array of todos. Each entry has an object of properties, including the todo item and whether or not it’s completed.

let todos = [
	{
		item: 'Plan surprise party for Ryder',
		completed: false
	},
	{
		item: 'Wash the dog',
		completed: true
	},
	{
		item: 'Watch Elemental',
		completed: true
	},
	{
		item: 'Read the Hobbit',
		completed: false
	}
];

For both filter() and find(), you pass in a callback function that receives each item in the array as an argument. You can run some check against that item, then return a boolean: true if it’s an item you want, and false if it’s not.

If you wanted to find all of the completed todos, you could do this…

// returns a new array with the "Wash the dog" and "Watch Element" objects
let completed = todos.filter(function (todo) {
	return todo.completed;
});

And to find the first completed item, you would instead do this…

// returns {item: 'Wash the dog', completed: true}
let firstCompleted = todos.find(function (todo) {
	return todo.completed;
});

Finding the last matching element

The findLast() method works the same way as the find() method, but finds the last matching item in an array instead of the first.

// returns {item: 'Watch Elemental', completed: true}
let lastCompleted = todos.findLast(function (todo) {
	return todo.completed;
});

Here’s a demo.

There are a handful of other ways you can do the same thing, but I think the easiest is to use the filter() method and grab the last item.

let completed = todos.filter(function (todo) {
	return todo.completed;
});
let lastCompleted = completed[completed.length - 1];

Here’s another demo.

Browser support (and a polyfill)

Like all of the methods in this series, Array.prototype.findLast() is supported in all major browsers, but is still too new to use without a polyfill (in my opinion).

Here’s a polyfill you can use until browser support catches up…

if (!Array.prototype.findLast) {
	Array.prototype.findLast = function (callback) {
		let temp = this.filter(callback);
		return temp[temp.length - 1];
	};
}

Once it does, you can delete the polyfill without having to refactor your code.