[英]Find index of same elements in array multiple times
I'd like to find an element's POSITIONS in same array without methods, with an algorithm... 我想在没有方法的情况下使用算法在同一数组中找到元素的位置 ...
Example : 范例 :
var a = [1,2,2,1,4,5,6]
to display positions of 1 : position 0 and 3
to display positions of 2 : position 1 and 2
What I have done so far: 到目前为止,我所做的是:
function count(array,element){
while(element in array){
return array.indexOf(element);
}
}
For getting all positions, you must walk whole array before return 为了获得所有位置,您必须在返回之前遍历整个数组
var a = [1,2,2,1,4,5,6]
function count(array,element){
var counts = [];
for (i = 0; i < array.length; i++){
if (array[i] === element) {
counts.push(i);
}
}
return counts;
}
count(a, 1); //returns [0,3]
count(a, 2); //returns [1,2]
I'd suggest: 我建议:
count (haystack, needle) {
return haystack.filter(function (el, index) {
if (el === needle) {
return index;
}
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.