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 remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: