javascript 如何在javascript数组中搜索相同值的多个索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/24241462/
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
How to search for multiple index(es) of same values in javascript array
提问by Capitaine
I have a 1 dimensional array like:
我有一个一维数组,如:
var abc = ['a','a','b','a','c']
Now I want to get back all the indexes of 'a'
, that is 0, 1 and 3.
现在我想取回 的所有索引'a'
,即 0、1 和 3。
Are there any simple solutions?
有什么简单的解决办法吗?
P.S.
聚苯乙烯
I know IndexOf
or jQuery.inArray()
. But they just returned the index of first matched element only
我知道IndexOf
或jQuery.inArray()
。但他们只返回第一个匹配元素的索引
回答by Matyas
You could extend the basic Array
Object
with the following method:
您可以Array
Object
使用以下方法扩展基本:
Array.prototype.multiIndexOf = function (el) {
var idxs = [];
for (var i = this.length - 1; i >= 0; i--) {
if (this[i] === el) {
idxs.unshift(i);
}
}
return idxs;
};
Then the operation
然后操作
var abc = ['a','a','b','a','c'];
abc.multiIndexOf('a');
would give you the result:
会给你结果:
[0, 1, 3]
Jsperf comparisonof unshift / push / push(reverse order)
unshift/push/push的jsperf对比(逆序)
回答by Sascha Wolf
Rather than using a for loop, you can use a while loop combined with indexOf
:
除了使用 for 循环,您还可以将 while 循环与indexOf
以下元素结合使用:
var array = [1, 2, 3, 4, 2, 8, 5],
value = 2,
i = -1,
indizes = [];
while((i = array.indexOf(value, i + 1)) !== -1) {
indizes.push(i);
}
This will return you [1, 4]
and of course could be combined with extending the prototype of Array
.
这将返回您[1, 4]
,当然可以与扩展Array
.
The second argument of indexOf
specifies where to start the search in the given array.
的第二个参数indexOf
指定在给定数组中开始搜索的位置。
回答by Barmar
AFAIK, there's no Javascript or jQuery function that does this in one step, you have to write a loop.
AFAIK,没有 Javascript 或 jQuery 函数可以一步完成此操作,您必须编写一个循环。
var indexes = [];
$.each(abc, function(i, val) {
if (val == "a") {
indexes.push(i);
}
}
回答by Parag Gangil
Do it this way :
这样做:
var abc = ['a','a','b','a','c'];
var abc = ['a','a','b','a','c'];
for (var i=0; i<abc.length; i++) {if(abc[i]=='a') {console.log(i)};}
for (var i=0; i<abc.length; i++) {if(abc[i]=='a') {console.log(i)};}
回答by Alireza
You also use reducefunction on the array and push the indexes to accumulated array, you need start with an empty array, the good thing about reduce is it's async and also time execution is faster than for loop, also it's a native function on array, look at the below, hope it's helping:
您还可以在数组上使用reduce函数并将索引推送到累积数组,您需要从一个空数组开始,reduce 的好处是它是异步的,而且时间执行速度比 for 循环快,它也是数组上的本机函数,看看下面的,希望对你有帮助:
var arr = [0, 1, 2, 3, 7, 2, 3, 4, 7, 8, 9, 2, 3];
function indexesOf(num) {
var reduced = arr.reduce(function(acc, val, ind, arr){
if(val === num){
acc.push(ind);
}
return acc;
}, []);
return reduced;
}
indexesOf(2); //[2, 5, 11]
回答by Frédéric Hamidi
You can take advantage of the fact that $.map()does not push values in its resulting array when the function you pass returns undefined
.
您可以利用这样一个事实,即当您传递的函数返回时$.map()不会在其结果数组中推送值undefined
。
Therefore, you can write:
因此,您可以编写:
var abc = ["a", "a", "b", "a", "c"];
var indices = $.map(abc, function(element, index) {
if (element == "a") {
return index;
}
});
回答by Cea
If your array size is fixed, then you can find the first occurrence in the array using indexOf()
. Use the found index value as starting point in indexOf()
to find an other occurrence.
如果您的数组大小是固定的,那么您可以使用indexOf()
. 使用找到的索引值作为起点indexOf()
来查找其他事件。
var firstOccurance = [your_array].indexOf(2)
var secondOccurance = [your_array].indexOf(2, firstOccurance + 1)
回答by Nina Scholz
You could use Array#reduce
with Array#concat
with a check for the wanted item, take the index or an empty array.
您可以使用Array#reduce
withArray#concat
检查所需项目,获取索引或空数组。
var abc = ['a', 'a', 'b', 'a', 'c'],
indices = abc.reduce((r, v, i) => r.concat(v === 'a' ? i : []), []);
console.log(indices);
ES5
ES5
var abc = ['a', 'a', 'b', 'a', 'c'],
indices = abc.reduce(function (r, v, i) {
return r.concat(v === 'a' ? i : []);
}, []);
console.log(indices);
回答by Jérémie Touzé
With ES6 syntax you could go with forEach and the ternary operator :
使用 ES6 语法,您可以使用 forEach 和三元运算符:
const abc = ['a','a','b','a','c']
let matchingIndexes = []
abc.forEach( (currentItem, index) => {
currentItem === 'a' ? matchingIndexes.push(index) : null
})
console.log(matchingIndexes) // [0, 1, 3]