【发布时间】:2020-01-13 13:56:48
【问题描述】:
找到与谓词匹配的数组项(不一定是索引,但有效)的最佳方法是什么(所以我不能直接比较这些项,忘记indexOf)从一个索引。
我想从数组中获取“下一个匹配”项,从当前位置开始。
下面是我目前的实现:
var currentIndex = 1;
var results = [
{status: 'AWAITING_APPROVAL'}, // Not matched
{status: 'APPROVED'},
{status: 'APPROVED'},
{status: 'APPROVED'},
{status: 'AWAITING_APPROVAL'},
{status: 'APPROVED'},
];
var nextIndex = results
.slice(currentIndex)
.findIndex(function (content) {
return content.status === 'AWAITING_APPROVAL';
});
if (nextIndex !== -1) {
nextIndex += currentIndex;
// Here we can use nextIndex which is 4
console.log(nextIndex);
}
当然,我可以只做一个基本的 for 循环/ifs,但我想知道是否有更好的方法(也许使用 lodash)。
【问题讨论】:
-
你的方法有什么问题?只需将
.findIndex()替换为.find()即可更轻松一些。 -
@Andreas 拼接复制了数组,不理想。我正在查看下面 Nina 的答案,这似乎符合我的要求
-
lodash的findIndex的第三个参数是要搜索的索引
-
@GruffBunny 是的!我错过了这一点,因为在 lodash 3.x 中并非如此,但这对下一个登陆这里的人很有用
标签: javascript arrays search lodash