你有比以下代码更智能的算法吗?

时间:2015-04-17 13:32:52

标签: javascript arrays count diff

我想按键计算一个数组。并计算它们的数量

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

1 个答案:

答案 0 :(得分: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))