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
什麼是預期的輸出?現在輸出什麼? –
http://stackoverflow.com/questions/10927722/jquery-compare-2-arrays-return-difference – adeneo
...和計數看例如http://stackoverflow.com/a/5668029/3703422 –