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

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

问题描述

假设我有一个对象数组:

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的值为某物的元素的最后一个索引。在这种情况下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...

推荐答案

您可以使用 findIndex 获取索引。

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')

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

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