匹配数组中的 3 个或更多相同元素并将它们添加到列表中

我试图在数组中找到 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,就是这样


拉丁的传说
浏览 192回答 3
3回答

慕妹3242003

您可以使用一个临时数组来收集相同的值,如果长度具有所需的最小长度,则推送此数组。function getMore(array, min) {&nbsp; &nbsp; var result = [],&nbsp; &nbsp; &nbsp; &nbsp; temp;&nbsp; &nbsp; array.forEach((v, i, a) => {&nbsp; &nbsp; &nbsp; &nbsp; if (v !== a[i - 1]) return temp = [v];&nbsp; &nbsp; &nbsp; &nbsp; temp.push(v);&nbsp; &nbsp; &nbsp; &nbsp; if (temp.length === min) result.push(temp);&nbsp; &nbsp; });&nbsp; &nbsp; return result;}console.log(getMore([2, 2, 2, 5, 5, 5, 3, 3, 3, 3], 3));

catspeake

使用 Array.prototype[reduce/map/filter] 的另一种解决方案const someArray = [2, 2, 2, 5, 5, 5, 3, 3, 3, 3, 9, 9];console.log(aggregate(someArray));function aggregate(arr) {&nbsp; return arr&nbsp; &nbsp; // retrieve unique values&nbsp; &nbsp; .reduce((acc, val) => !acc.includes(val) && acc.concat(val) || acc, [])&nbsp; &nbsp; // use unique values to map arr values to strings&nbsp;&nbsp; &nbsp; // if number of matches >= 3&nbsp; &nbsp; .map(val => {&nbsp; &nbsp; &nbsp; const filtered = arr.filter(v => v == val);&nbsp; &nbsp; &nbsp; return filtered.length > 2 ? filtered.join("") : false&nbsp; &nbsp; &nbsp;})&nbsp; &nbsp; &nbsp;// filter non falsy values&nbsp; &nbsp; &nbsp;.filter(val => val);}

慕妹3146593

你可以做这样的事情:var grid = [ 1, 1, 2, 3, 4, 5 ];var hashMap = {};for( var i = 0; i < grid.length; i++ ) {&nbsp; if( hashMap.hasOwnProperty( grid[i] ) ) {&nbsp; &nbsp; hashMap[ grid[i] ]++;&nbsp; } else {&nbsp; &nbsp; hashMap[ grid[i] ] = 1;&nbsp; }}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript