2015-04-17 46 views
0

我想按鍵計數數組。差異比較及對盡數你有什麼聰明的算法比下面的代碼

var count = function(arr) { 
    var result = {}; 
    for (var i = 0 ; i < arr.length ; i++) { 
        var key = arr[i]; 
        result[key] = ++result[key] || 1; 
    } 
    return result 
}; 
var diff = function(first, second) { 
    var first_copy = {}; 
    for (var key in first) { 
        first_copy[key] = first[key]; 
        if (second[key]) { 
            first_copy[key] -= second[key] 
        } 
    } 
    return first_copy; 
}; 
var first = [1, 1, 1, 2, 2, 3], 
    second = [1, 1, 2, 2, 2]; 
first = count(first); 
second = count(second); 
console.log(diff(first, second)); 
console.log(diff(second, first)); 

期望輸出

Object {1: 1, 2: -1, 3: 1} // first - second 
Object {1: -1, 2: 1}  // second - first 
+0

什麼是預期的輸出?現在輸出什麼? –

+0

http://stackoverflow.com/questions/10927722/jquery-compare-2-arrays-return-difference – adeneo

+0

...和計數看例如http://stackoverflow.com/a/5668029/3703422 –

回答

1

如果你的目標是提高可讀性,我會使用underscorejs(http://underscorejs.org/)建議。

這裏是你如何可以underscorejs做到這一點:

function diff(o1, o2){ 
return _.chain(_.keys(o1)) 
    .map(function(e){ 
    return [e, (o1[e] - (o2[e] || 0))]; 
    }) 
    .object() 
    .value(); 
} 

first = [1, 1, 1, 2, 2, 3] 
second = [1, 1, 2, 2, 2] 

firstCount = _.countBy(first, _.id) 
secondCount = _.countBy(second, _.id) 

console.log(diff(firstCount, secondCount)) 
console.log(diff(secondCount, firstCount))