Let's say I have an array of objects:
[ { 'a': 'something', 'b':12 }, { 'a': 'something', 'b':12 }, { 'a': 'somethingElse', 'b':12 }, { 'a': 'something', 'b':12 }, { 'a': 'somethingElse', 'b':12 } ]
What would be the cleanest way to get the last index of an element where a
has the value 'something'
- in this case index 3? Is there any way to avoid loops?
Subtracting 1 from the length of an array gives the index of the last element of an array using which the last element can be accessed. The reason we are subtracting 1 from the length is, in JavaScript, the array index numbering starts with 0. i.e. 1st element's index would 0.
Use the findIndex() method to get the index of an array element that matches a condition. The method takes a function and returns the index of the first element in the array, for which the condition is satisfied. If the condition is never met, the findIndex method returns -1 .
The lastIndexOf() method returns the last index (position) of a specified value. The lastIndexOf() method returns -1 if the value is not found. The lastIndexOf() starts at a specified index and searches from right to left. By defalt the search starts at the last element and ends at the first.
Here's a reusable typescript version which mirrors the signature of the ES2015 findIndex function:
/** * Returns the index of the last element in the array where predicate is true, and -1 * otherwise. * @param array The source array to search in * @param predicate find calls predicate once for each element of the array, in descending * order, until it finds one where predicate returns true. If such an element is found, * findLastIndex immediately returns that element index. Otherwise, findLastIndex returns -1. */ export function findLastIndex<T>(array: Array<T>, predicate: (value: T, index: number, obj: T[]) => boolean): number { let l = array.length; while (l--) { if (predicate(array[l], l, array)) return l; } return -1; }
You can use findIndex
to get index. This will give you first index, so you will have to reverse the array.
var d = [{'a': "something", 'b':12}, {'a': "something", 'b':12}, {'a': "somethingElse", 'b':12}, {'a': "something", 'b':12}, {'a': "somethingElse", 'b':12}] function findLastIndex(array, searchKey, searchValue) { var index = array.slice().reverse().findIndex(x => x[searchKey] === searchValue); var count = array.length - 1 var finalIndex = index >= 0 ? count - index : index; console.log(finalIndex) return finalIndex; } findLastIndex(d, 'a', 'something') findLastIndex(d, 'a', 'nothing')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With