2015-04-23 3 views
-2

У меня есть функция для поиска одинаковых номеров:Как добавить совпадение в двумерном массиве?

var arr = [0, 0, 4, 8, 8, 10, 45, 0, 23, 3 ,8]; 
arr.filter(function (item, index, array) {  
    return array.indexOf(item) !== array.lastIndexOf(item); // [0, 0, 8, 8, 0, 8] 
}); 

Но, мне нужно создать двумерный массив для отдельных матчей.

Таким образом, результат должен быть: [[0, 0, 0], [8, 8, 8]]

ответ

0
uniqueCount =[0, 0, 4, 8, 8, 10, 45, 0, 23, 3 ,8]; 

var count = {}; 
var twoDimArray = []; 
uniqueCount.forEach(function(i) { count[i] = (count[i]||0)+1; }); 
for(key in count){ 
    var array = []; 
    for (i=0; i<count[key]; i++){ 
     array.push(key); 
    } 
    twoDimArray.push(array); 
} 
alert(twoDimArray); 
//alert(JSON.stringify(count)); 

Demo

0
// source array 
var arr = [0, 0, 4, 8, 8, 10, 45, 0, 23, 3, 8]; 
// temporary variable for distribution 
var oTemp = {}; 
// your result array 
var aResult = []; 
// make distribution 
arr.forEach(function (i) { 
    //test if item exist, if so add one, otherwise assign 1 
    oTemp[i] = oTemp[i] + 1 || 1; 
}); 
// make result array 
Object.keys(oTemp).forEach(function (i) { 
    // according to requirement, only more than one count is used 
    if (oTemp[i] > 1) { 
     // push a new array, which is filled with the count to the result 
     aResult.push(Array.apply(null, { length: oTemp[i] }).map(function() { return i; })); 
    } 
}); 

Ваш результат находится в aResult.

Смежные вопросы