[英]How to get index of all occurences of the same value in an Array?
I am using a set of numerical values in an array where certain values are be repeated. 我在数组中使用一组数值,其中重复某些值。 I want to find the indices of ALL of the occurrences of a repeated value.
我想找到重复值的所有出现的索引。
For example, I have the following code using indexOf()
: 例如,我使用
indexOf()
有以下代码:
var dataset = [2,2,4,2,6,4,7,8];
return dataset.indexOf(2);
But this only gives the index of the first occurrence of 2
. 但这只给出了第一次出现
2
的索引。 (ie it returns the value 0
.) (即它返回值
0
)
However, I want the indices for ALL the occurrences of 2
to be returned (ie 0,1,3
). 但是,我希望返回所有出现的
2
的索引(即0,1,3
)。 How can I do this? 我怎样才能做到这一点? (I know I could use a
for
loop, but I'm wondering if there's a better way to do this having without iterating through the whole array. Basically, I'm trying to save the overhead of explicitly iterating through the whole array.) (我知道我可以使用
for
循环,但我想知道是否有更好的方法来完成这个而不需要遍历整个数组。基本上,我试图节省显式迭代整个数组的开销。)
@Bagavatu: If you don't want a for loop you could try this fiddle - @Bagavatu:如果你不想要for循环你可以试试这个小提琴 -
var dataset = [2,2,4,2,6,4,7,8];
var results = [];
var ind
// the while loop stops when there are no more found
while( ( ind = dataset.indexOf( 2 ) ) != -1 ){
results.push( ind + results.length )
dataset.splice( ind, 1 )
}
return results;
NOTE: using a for loop would be MUCH quicker. 注意:使用for循环会更快。 See comments.
看评论。
var dataset = [2,2,4,2,6,4,7,8];
var results = [];
for ( i=0; i < dataset.length; i++ ){
if ( dataset[i] == 2 ){
results.push( i );
}
}
return results;
You can use the filter()
method of the Array
object to handle nicely: 您可以使用
Array
对象的filter()
方法来很好地处理:
var dataset = [2, 2, 4, 2, 6, 4, 7, 8];
var indexs = [];
dataset.filter(function(elem, index, array){
if(elem == 2) {
indexs.push(index);
}
});
alert(indexs);
And here is some more documentation on the filter() method , as well as a fallback for older browsers. 这里有一些关于filter()方法的文档 ,以及旧版浏览器的后备文件。
Here you have an example: Try if yourself 这里有一个例子: 尝试自己
var dataset = [2,2,4,2,6,4,7,8];
// We get the first indexOf number 2
var prev = dataset.indexOf(2);
// While we find indexes we keep searching
while (prev != -1) {
alert(prev);
// we get the indexOf number 2 starting in the previous position + 1
prev = dataset.indexOf(2, prev + 1);
}
Looks like this functionality may not be possible out-of-the-box, but there is a 'plugin' available here by creating a Array.prototype.allIndexOf
function. 貌似这个功能可能无法出的现成的,但有一个“插件”可以在这里创建一个
Array.prototype.allIndexOf
功能。
It still iterates over the entire list (which is required), but it abstracts the logic a little bit. 它仍然遍历整个列表(这是必需的),但它略微抽象了逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.