jQuery 获取数组内对象的索引,匹配条件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15997879/
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
Get the index of the object inside an array, matching a condition
提问by amp
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"
,我想获得 index 1
。
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.
我看到.indexOf()
但认为它用于简单的数组,如["a1","a2",...]
. 我也检查过,$.grep()
但这返回对象,而不是索引。
回答by georg
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. For Internet Explorer, there's a polyfill on the linked page.
它在 Google Chrome、Firefox 和 Edge 中受支持。对于 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.
与大多数优化一样,这应该谨慎应用,并且仅在实际需要时才应用。
回答by T.J. Crowder
How can I get the index of the object tha match a condition (without iterate along the array)?
如何获取与条件匹配的对象的索引(不沿数组迭代)?
You cannot, somethinghas to iterate through the array (at least once).
你不能,有些东西必须遍历数组(至少一次)。
If the condition changes a lot, then you'll have to loop through and look at the objects therein to see if they match the condition. However, on a system with ES5 features (or if you install a shim), that iteration can be done fairly concisely:
如果条件变化很大,那么您将不得不循环并查看其中的对象以查看它们是否与条件匹配。但是,在具有 ES5 功能的系统上(或者如果您安装了 shim),该迭代可以相当简洁地完成:
var index;
yourArray.some(function(entry, i) {
if (entry.prop2 == "yutu") {
index = i;
return true;
}
});
That uses the new(ish) Array#some
function, which loops through the entries in the array until the function you give it returns true. The function I've given it saves the index of the matching entry, then returns true
to stop the iteration.
这使用了 new(ish)Array#some
函数,它循环遍历数组中的条目,直到您给它的函数返回 true。我给它的函数保存匹配条目的索引,然后返回true
以停止迭代。
Or of course, just use a for
loop. Your various iteration options are covered in this other answer.
或者当然,只需使用for
循环。您的各种迭代选项包含在另一个答案中。
But if you're always going to be using the same property for this lookup, and if the property values are unique, you can loop just once and create an object to map them:
但是,如果您总是要在此查找中使用相同的属性,并且属性值是唯一的,那么您可以只循环一次并创建一个对象来映射它们:
var prop2map = {};
yourArray.forEach(function(entry) {
prop2map[entry.prop2] = entry;
});
(Or, again, you could use a for
loop or any of your other options.)
(或者,同样,您可以使用for
循环或任何其他选项。)
Then if you need to find the entry with prop2 = "yutu"
, you can do this:
然后,如果您需要找到带有 的条目prop2 = "yutu"
,您可以这样做:
var entry = prop2map["yutu"];
I call this "cross-indexing" the array. Naturally, if you remove or add entries (or change their prop2
values), you need to update your mapping object as well.
我称之为“交叉索引”数组。自然地,如果您删除或添加条目(或更改它们的prop2
值),您也需要更新您的映射对象。
回答by aliak
回答by David Castro
var CarId = 23;
//x.VehicleId property to match in the object array
var carIndex = CarsList.map(function (x) { return x.VehicleId; }).indexOf(CarId);
And for basic array numbers you can also do this:
对于基本数组编号,您也可以这样做:
var numberList = [100,200,300,400,500];
var index = numberList.indexOf(200); // 1
You will get -1 if it cannot find a value in the array.
如果在数组中找不到值,您将得到 -1。
回答by Nina Scholz
var index;
yourArray.some(function (elem, i) {
return elem.prop2 === 'yutu' ? (index = i, true) : false;
});
Iterate over all elements of array. It returns either the index and true or false if the condition does not match.
迭代数组的所有元素。如果条件不匹配,则返回索引和 true 或 false。
Important is the explicit return value of true (or a value which boolean result is true). The single assignment is not sufficient, because of a possible index with 0 (Boolean(0) === false), which would not result an error but disables the break of the iteration.
重要的是 true 的显式返回值(或布尔结果为 true 的值)。单个赋值是不够的,因为可能的索引为 0 (Boolean(0) === false),这不会导致错误但会禁用迭代中断。
Edit
编辑
An even shorter version of the above:
上面更短的版本:
yourArray.some(function (elem, i) {
return elem.prop2 === 'yutu' && ~(index = i);
});
回答by GibboK
You can use the Array.prototype.some()in the following way (as mentioned in the other answers):
您可以通过以下方式使用Array.prototype.some()(如其他答案中所述):
https://jsfiddle.net/h1d69exj/2/
https://jsfiddle.net/h1d69exj/2/
function findIndexInData(data, property, value) {
var result = -1;
data.some(function (item, i) {
if (item[property] === value) {
result = i;
return true;
}
});
return result;
}
var data = [{prop1:"abc",prop2:"qwe"},{prop1:"bnmb",prop2:"yutu"},{prop1:"zxvz",prop2:"qwrq"}]
alert(findIndexInData(data, 'prop2', "yutu")); // shows index of 1
回答by Rambabu Bommisetti
I have seen many solutions in the above.
我在上面看到了很多解决方案。
Here I am using map function to find the index of the search text in an array object.
在这里,我使用 map 函数在数组对象中查找搜索文本的索引。
I am going to explain my answer with using students data.
我将使用学生数据来解释我的答案。
step 1: create array object for the students(optional you can create your own array object).
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];
step 2: Create variable to search text
var studentNameToSearch = "Divya";
step 3: Create variable to store matched index(here we use map function to iterate).
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);
第 1 步:为学生创建数组对象(可选,您可以创建自己的数组对象)。
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];
第 2 步:创建变量以搜索文本
var studentNameToSearch = "Divya";
第 3 步:创建变量来存储匹配的索引(这里我们使用 map 函数进行迭代)。
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);
var students = [{name:"Rambabu",htno:"1245"},{name:"Divya",htno:"1246"},{name:"poojitha",htno:"1247"},{name:"magitha",htno:"1248"}];
var studentNameToSearch = "Divya";
var matchedIndex = students.map(function (obj) { return obj.name; }).indexOf(studentNameToSearch);
console.log(matchedIndex);
alert("Your search name index in array is:"+matchedIndex)
回答by pranabesh chand
function findIndexByKeyValue(_array, key, value) {
for (var i = 0; i < _array.length; i++) {
if (_array[i][key] == value) {
return i;
}
}
return -1;
}
var a = [
{prop1:"abc",prop2:"qwe"},
{prop1:"bnmb",prop2:"yutu"},
{prop1:"zxvz",prop2:"qwrq"}];
var index = findIndexByKeyValue(a, 'prop2', 'yutu');
console.log(index);
回答by SagiSergeNadir
One step using Array.reduce() - no jQuery
一步使用 Array.reduce() - 没有 jQuery
var items = [{id: 331}, {id: 220}, {id: 872}];
var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
if(item.id === searchIndexForId) {
console.log('found!');
searchIndex = index;
}
return searchIndex;
}, null);
will return null
if index was not found.
null
如果未找到索引,将返回。
回答by Rishabh
Why do you not want to iterate exactly ? The new Array.prototype.forEachare great for this purpose!
为什么你不想精确迭代?新的Array.prototype.forEach非常适合这个目的!
You can use a Binary Search Tree to find via a single method call if you want. This is a neat implementation of BTree and Red black Search tree in JS - https://github.com/vadimg/js_bintrees- but I'm not sure whether you can find the index at the same time.
如果需要,您可以使用二叉搜索树通过单个方法调用进行查找。这是 JS 中 BTree 和红黑搜索树的巧妙实现 - https://github.com/vadimg/js_bintrees- 但我不确定您是否可以同时找到索引。