Find last index of element inside array by certain condition

In Javascript, the following snippet of code pass over an array of objects and does filter the array based on certain conditions, the output of this process would be an array of items if they met the conditions or an empty array of zero items.

arrayOfObjects.filter((object) => object.color === 'certain condition')

There’s another option to do that, which is using the built-in function included in the JS array prototype findLastIndex.

Let’s explore both!


Examples:

Consider we have an array of car models as the following:

const arrayOfCarModels = [
  {
    color: 'red',
    type: 'cabrio',
    capacity: 2,
  },
  {
    color: 'red',
    type: 'station wagon',
    registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 5,
  },
  {
    color: 'green',
    type: 'cabrio',
    capacity: 3,
  },
  {
    color: 'black',
    type: 'suv',
    capacity: 7,
  },
  {
    color: 'red',
    type: 'micro',
    capacity: 2,
  },
];
And we need to get the last item from the array that meets the following conditions:
  • Car color is red.
  • Car capacity is 2.

1- Using findLastIndex method.

The findLastIndex() method 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.

const arrayOfCarModels = [
  {
    color: 'red',
    type: 'cabrio',
    capacity: 2,
  },
  {
    color: 'red',
    type: 'station wagon',
    registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 5,
  },
  {
    color: 'green',
    type: 'cabrio',
    capacity: 3,
  },
  {
    color: 'black',
    type: 'suv',
    capacity: 7,
  },
  {
    color: 'red',
    type: 'micro',
    capacity: 2,
  },
];

console.log(arrayOfCarModels.findLastIndex(
(obj) => obj.color === "red" && obj.capacity === 2)
);

// Output:
// 4

In the example above, we’ve used findLastIndex over an array of objects to find the last element of the array that meets our conditions. and as shown in the output 4, which is the index of the last object in the array that does meet the conditions above.

2- Using custom implementation.

In order to do that we need to pass over the array and filter the items as the following:

let filteredModels = [];

filteredModels = arrayOfCarModels.filter((carModel) => carModel.color === 'red' && carModel.capacity === 2);

console.log(filteredModels);

The results of this process, as we mentioned before, would be an array of items meet the conditions.

// Output
// [
//   { color: 'red', type: 'cabrio', capacity: 2 },
//   { color: 'red', type: 'micro', capacity: 2 },
// ]

Now we have the results that meet the conditions above, and the last item of the output is what we’re looking for, so we can basically access it directly through:

filteredModels[filteredModels.length - 1]

Putting all the code together:

const arrayOfCarModels = [
  {
    color: 'red',
    type: 'cabrio',
    capacity: 2,
  },
  {
    color: 'red',
    type: 'station wagon',
    registration: 'Sat Mar 03 2018 01:00:00 GMT+0100 (GMT+01:00)',
    capacity: 5,
  },
  {
    color: 'green',
    type: 'cabrio',
    capacity: 3,
  },
  {
    color: 'black',
    type: 'suv',
    capacity: 7,
  },
  {
    color: 'red',
    type: 'micro',
    capacity: 2,
  },
];

let filteredModels = [];

filteredModels = arrayOfCarModels.filter((carModel) => carModel.color === 'red' && carModel.capacity === 2);

if (filteredModels && filteredModels.length > 0) {
  console.log(filteredModels[filteredModels.length - 1]);
}

// Output:
// { color: 'red', type: 'micro', capacity: 2 }

That’s it for How To Find the last index of element inside an array by certain condition In JavaScript

As always happy coding!

Photo from Unsplash.

Related Posts

How to Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: