获取数组内对象的索引,匹配条件 [英] Get the index of the object inside an array, matching a condition

查看:24
本文介绍了获取数组内对象的索引,匹配条件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个这样的数组:

[{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"},...]

如何在不遍历整个数组的情况下获取与条件匹配的对象的索引?

How can I get the index of the object that matches a condition, without iterating over the entire array?

例如,给定prop2=="yutu",我想得到索引1.

For instance, given prop2=="yutu", I want to get index 1.

我看到了 .indexOf() 但认为它用于像 ["a1","a2",...] 这样的简单数组.我还检查了 $.grep() 但这返回的是对象,而不是索引.

I saw .indexOf() but think it's used for simple arrays like ["a1","a2",...]. I also checked $.grep() but this returns objects, not the index.

推荐答案

截至 2016 年,您应该使用 Array.findIndex(ES2015/ES6 标准):

As of 2016, you're supposed to use Array.findIndex (an ES2015/ES6 standard) for this:

a = [
  {prop1:"abc",prop2:"qwe"},
  {prop1:"bnmb",prop2:"yutu"},
  {prop1:"zxvz",prop2:"qwrq"}];
    
index = a.findIndex(x => x.prop2 ==="yutu");

console.log(index);

它在 Google Chrome、Firefox 和 Edge 中受支持.对于 Internet Explorer,链接页面上有一个 polyfill.

It's supported in Google Chrome, Firefox and Edge. For Internet Explorer, there's a polyfill on the linked page.

性能说明

函数调用开销很大,因此对于非常大的数组,一个简单的循环会比 findIndex 执行得更好:

Function calls are expensive, therefore with really big arrays a simple loop will perform much better than findIndex:

let test = [];

for (let i = 0; i < 1e6; i++)
    test.push({prop: i});


let search = test.length - 1;
let count = 100;

console.time('findIndex/predefined function');
    let fn = obj => obj.prop === search;

    for (let i = 0; i < count; i++)
        test.findIndex(fn);
console.timeEnd('findIndex/predefined function');


console.time('findIndex/dynamic function');
    for (let i = 0; i < count; i++)
        test.findIndex(obj => obj.prop === search);
console.timeEnd('findIndex/dynamic function');


console.time('loop');
    for (let i = 0; i < count; i++) {
        for (let index = 0; index < test.length; index++) {
            if (test[index].prop === search) {
                break;
            }
        }
    }
console.timeEnd('loop');

与大多数优化一样,这应该谨慎应用,并且仅在实际需要时才应用.

As with most optimizations, this should be applied with care and only when actually needed.

这篇关于获取数组内对象的索引,匹配条件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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