Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
358 views
in Technique[技术] by (71.8m points)

javascript - 获取匹配条件的数组内对象的索引(Get the index of the object inside an array, matching a condition)

I have an array like this:

(我有一个像这样的数组:)

[{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?

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

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

(例如,给定prop2=="yutu" ,我想获取索引1 。)

I saw .indexOf() but think it's used for simple arrays like ["a1","a2",...] .

(我看到了.indexOf()但认为它用于简单的数组,例如["a1","a2",...] 。)

I also checked $.grep() but this returns objects, not the index.

(我还检查了$.grep()但这返回对象,而不是索引。)

  ask by amp translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

(从2016年开始,您应该为此使用Array.findIndex (ES2015 / ES6标准):)

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

It's supported in Google Chrome, Firefox and Edge.

(Google Chrome,Firefox和Edge支持该功能。)

For Internet Explorer, there's a polyfill on the linked page.

(对于Internet Explorer,在链接页面上有一个polyfill。)

Performance note

(业绩说明)

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

(函数调用是昂贵的,因此对于非常大的数组,简单的循环将比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.

(与大多数优化一样,应谨慎且仅在实际需要时才应用此优化。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...