我试图在数组中查找 3 个或更多匹配项,但它仅匹配前 3 个,而与数组的其余部分不匹配。如果有人能提供帮助那就太好了:)
var grid = [2,2,2,5,5,5,3,3,3,3];
checkResults();
function checkResults(){
var list_matches = []; // store all matches found
var listcurrent = []; // store current
var maxitems = 3;
var last = -1; // last cell
for(let j =0; j < grid.length; ++j){
let item = grid[j];
// check if last is null
if(last == -1){
// add first item
listcurrent.push(item);
last = item;
console.log("Added: "+item);
continue;
}
let wasMatch = false;
// check match
if(item == last){
wasMatch = true;
listcurrent.push(item);
last = item;
console.log("Added Match: "+item);
}
if(!wasMatch){
console.log("Not matched: " + item);
if(listcurrent.length >= maxitems){
list_matches.push(listcurrent);
}
// reset to null
last = -1;
listcurrent = [];
}
}
console.log(list_matches);
console.log("Cols: " + grid.length);
}
预期结果:来自 [2,2,2,5,5,5,3,3,3,3];
0:222
1:555
2:3333
当前输出为: 0: 222 就是这样
最佳答案
您可以使用一个临时数组来收集相同的值,如果长度达到所需的最小长度,则推送该数组。
function getMore(array, min) {
var result = [],
temp;
array.forEach((v, i, a) => {
if (v !== a[i - 1]) return temp = [v];
temp.push(v);
if (temp.length === min) result.push(temp);
});
return result;
}
console.log(getMore([2, 2, 2, 5, 5, 5, 3, 3, 3, 3], 3));
关于javascript - 匹配数组中的 3 个或更多相同元素并将它们添加到列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58808092/