How to find the last matching Object in array of Objects with JavaScript?

Estimated read time 1 min read

You can use the Array.prototype.reverse() and Array.prototype.find() methods to find the last matching object in an array of objects that meets certain conditions. The find method takes a callback function as its argument, which should return a boolean value indicating whether the current object meets the desired conditions.

Here’s an example that demonstrates how to find the last object in an array of objects with a certain property value:

const arr = [
  { id: 1, name: 'John' },
  { id: 2, name: 'Jane' },
  { id: 3, name: 'Jim' },
  { id: 4, name: 'Jane' }

const lastObject = arr.reverse().find(function(obj) {
  return === 'Jane';

const result = arr[arr.length - 1 - arr.indexOf(lastObject)];

console.log(result); // { id: 4, name: 'Jane' }

In this example, we use the Array.prototype.reverse() method to reverse the array, and then use Array.prototype.find() to find the last object with the property name equal to 'Jane'. Finally, we use the Array.prototype.indexOf() method to find the index of the found object in the original, non-reversed array and use that to find the last matching object.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply