按特定条件查找数组内元素的最后一个索引 [英] Find last index of element inside array by certain condition

查看:44
本文介绍了按特定条件查找数组内元素的最后一个索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个对象数组:

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}
]

获取元素的最后一个索引的最简洁的方法是什么,其中 a 的值为 'something'.在这种情况下 3. 有没有办法避免循环...

What would be the most cleanest way to get the last index of the element where a has the value 'something'. In this case 3. Is there any way to avoid loops...

推荐答案

这是一个可重用的打字稿版本,它反映了 ES2015 findIndex 函数的签名:

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;
}

这篇关于按特定条件查找数组内元素的最后一个索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆