JS如果有两个以上重复项,则在数组中查找重复值的索引 [英] JS Find indices of duplicate values in array if there are more than two duplicates
问题描述
我要在连续游戏中创建三个坐标平面,所以我必须找出数组BUT WITHOUT sorting array中是否存在三个具有相同值的数字,因为该数组表示添加到坐标点上的点的x坐标在比赛中协调飞机... 例如,假设我已经向x坐标存储在下一个数组中的坐标平面添加了6个点:
I'm creating coordinate plane Three in a row game so I have to find out if there are three numbers of the same value in the array BUT WITHOUT sorting array because the array represents the x-coordinates of the points added to the coordinate plane during the game... For example, let's say that I've added 6 points to the coordinate plane with x-coordinates stored in next array:
var arr = [2,2,3,2,7,3];
我需要一个循环,该循环将仅对值2的出现进行计数,因为数字2在数组中出现3次,因此输出应为一个新数组(例如名为indexs的数组),其精确索引为nmb 2出现的次数在……...
I need the loop that will count only the occurrences of the value 2 because the number 2 occurs 3 times in array, so the output should be a new array (for example array named indices) with the exact indices of nmb 2 occurrences in arr...
indices = [0,1,3]
如果某个值的出现次数少于3次,则循环应在到达arr末尾时重置".
The loop should therefor "reset" when comes to the end of the arr if the number of occurrences of some value is less than 3...
我已经尝试了下一个代码,但是它不能像我上面描述的那样工作,因为它也计算3的出现次数...因此,如果value,它将不会重置"数量少于2 ...
I've tried the next code, but it doesn't work like I've described above because it counts the number of occurrences of the number 3 as well... so, it won't "reset" if value count is less than 2...
var arr = [2,2,3,2,7,3];
var index = [];
var count = 0;
var current;
for(var i = 0;i<arr.length;i++){
current = arr[i];
//-------------------------------
for(var j=i+1;j<arr.length;j++){
if(arr[j]===current){
count++;
index.push(j);
//+++++++++++
if(j===arr.length-1){
if(count<2){
count = 0;
index = [];
i++;
}
else{
index.unshift(i);
break;
}
}
//+++++++++++
}
}
//-------------------------------
}
alert(index);
感谢您的帮助或建议...
Thanks for any help or advice...
亚历山德拉(Aleksandra)
Aleksandra
推荐答案
是的,使用一些逻辑...
Yes, using some logic...
var arr = [2, 2, 3, 2, 7, 3];
function showDupPos(arr, mindups) {
mindups = mindups || 2;
var result = [];
var positions = {};
// collect all positions
arr.forEach(function(value, pos) {
positions[value] = positions[value] || [];
positions[value].push(pos);
});
//check how much of same value in string
Object.keys(positions).forEach(function(value) {
var posArray = positions[value];
if (posArray.length > mindups) {
result = result.concat(posArray);
}
});
return result.sort();
}
console.log(showDupPos(arr));
这篇关于JS如果有两个以上重复项,则在数组中查找重复值的索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!