Javascript 在对象数组中,找到属性与搜索匹配的对象索引的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10557486/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
In an array of objects, fastest way to find the index of an object whose attributes match a search
提问by Petrov
I've been surfing around a little trying to find an efficient way to do this, but have gotten nowhere. I have an array of objects that looks like this:
我一直在四处冲浪,试图找到一种有效的方法来做到这一点,但一无所获。我有一个看起来像这样的对象数组:
array[i].id = some number;
array[i].name = some name;
What i want to do is to find the INDEXES of the objects where id is equal to, for example, one of 0,1,2,3 or 4. I suppose I could just do something like :
我想要做的是找到 id 等于的对象的索引,例如,0、1、2、3 或 4 之一。我想我可以这样做:
var indexes = [];
for(i=0; i<array.length; i++) {
(array[i].id === 0) ? { indexes[0] = i }
(array[i].id === 1) ? { indexes[1] = i }
(array[i].id === 2) ? { indexes[2] = i }
(array[i].id === 3) ? { indexes[3] = i }
(array[i].id === 4) ? { indexes[4] = i }
}
While this would work, it looks to be quite expensive and slow (not to mention ugly), especially if array.length could be large. Any ideas on how to spruce this up a bit? I thought of using array.indexOf somehow but I don't see how to force the syntax. This
虽然这可行,但它看起来非常昂贵且缓慢(更不用说丑陋了),尤其是当 array.length 可能很大时。关于如何修饰它的任何想法?我想以某种方式使用 array.indexOf 但我不知道如何强制使用语法。这个
array.indexOf(this.id === 0);
for example, returns undefined, as it probably should. Thanks in advance!
例如,返回 undefined,因为它可能应该。提前致谢!
回答by Pablo Francisco Pérez Hidalgo
Maybe you would like to use higher-order functions such as "map". Assuming you want search by 'field' attribute:
也许您想使用诸如“map”之类的高阶函数。假设您想按 'field' 属性搜索:
var elementPos = array.map(function(x) {return x.id; }).indexOf(idYourAreLookingFor);
var objectFound = array[elementPos];
回答by Umair Ahmed
The simplest and easiest way to find element index in array.
在数组中查找元素索引的最简单和最简单的方法。
ES5 syntax:[{id:1},{id:2},{id:3},{id:4}].findIndex(function(obj){return obj.id == 3})
ES5 语法:[{id:1},{id:2},{id:3},{id:4}].findIndex(function(obj){return obj.id == 3})
ES6 syntax:[{id:1},{id:2},{id:3},{id:4}].findIndex(obj => obj.id == 3)
ES6 语法:[{id:1},{id:2},{id:3},{id:4}].findIndex(obj => obj.id == 3)
回答by jbabey
The new Array method .filter()would work well for this:
新的 Array 方法.filter()可以很好地解决这个问题:
var filteredArray = array.filter(function (element) {
return element.id === 0;
});
jQuery can also do this with .grep()
jQuery 也可以使用.grep()做到这一点
edit: it is worth mentioning that both of these functions just iterate under the hood, there won't be a noticeable performance difference between them and rolling your own filter function, but why re-invent the wheel.
编辑:值得一提的是,这两个函数只是在引擎盖下迭代,它们与滚动您自己的过滤器函数之间不会有明显的性能差异,但为什么要重新发明轮子。
回答by PirateApp
If you care about performance, dont go with findor filteror mapor any of the above discussed methods
如果您关心性能,请不要使用find或filter或map或任何上述讨论的方法
Here is an example demonstrating the fastest method. HEREis the link to the actual test
这是一个演示最快方法的示例。这是实际测试的链接
Setup block
设置块
var items = []
for(var i = 0; i < 1000; i++) {
items.push({id: i + 1})
}
var find = 523
Fastest Method
最快的方法
var index = -1
for(var i = 0; i < items.length; i++) {
if(items[i].id === find) {
index = i;
break;
}
}
Slower Methods
较慢的方法
items.findIndex(item => item.id === find)
SLOWEST method
最慢的方法
items.map(item => item.id).indexOf(find);
回答by Nina Scholz
array.forEach(function (elem, i) { // iterate over all elements of array
indexes[elem.id] = i; // take the found id as index for the
}); // indexes array and assign i
the result is a look up list for the id. with the given id we get the index of the record.
结果是该 id 的查找列表。使用给定的 id 我们得到记录的索引。
回答by Elliot Bonneville
var indices = [];
var IDs = [0, 1, 2, 3, 4];
for(var i = 0, len = array.length; i < len; i++) {
for(var j = 0; j < IDs.length; j++) {
if(array[i].id == ID) indices.push(i);
}
}
回答by enapupe
Since there's no answer using regular array find
:
由于使用常规数组没有答案find
:
var one = {id: 1, name: 'one'};
var two = {id: 2, name:'two'}
var arr = [one, two]
var found = arr.find((a) => a.id === 2)
found === two // true
arr.indexOf(found) // 1
回答by Silve2611
A new way using ES6
一种使用 ES6 的新方式
let picked_element = array.filter(element => element.id === 0);
回答by PulpDood
const index = array.findIndex(item => item.id === 'your-id');
const index = array.findIndex(item => item.id === 'your-id');
This should get you the index of item in array with id === your-id
这应该为您提供 id === your-id 数组中项目的索引
array = [ {id:1}, {id:2} ];
const index = array.findIndex(item => item.id === 2);
console.log(index);
回答by trungk18
To summary all of the great answer above and additional of my answer regarding find all the indexes occurred from some of the comment.
总结上面所有的好答案,以及我关于从一些评论中找到所有索引的附加答案。
- To return the index of the first occurrence.
- 返回第一次出现的索引。
const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 2 }];
const idYourAreLookingFor = 2;
//ES5
//Output: 1
array.map(function (x) { return x.id; }).indexOf(idYourAreLookingFor);
//ES6
//Output: 1
array.findIndex(obj => obj.id === idYourAreLookingFor);
- To return the index array of all occurrences, using reduce.
- 要返回所有出现的索引数组,请使用reduce。
const array = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 2 }]
const idYourAreLookingFor = 2;
//ES5
//Output: [1, 4]
array.reduce(function (acc, obj, i) {
if (obj.id === idYourAreLookingFor)
acc.push(i);
return acc;
}, []);
//ES6
//Output: [1, 4]
array.reduce((acc, obj, i) => (obj.id === idYourAreLookingFor) ? acc.concat(i) : acc, [])