Closed. This question needs details or clarity。它当前不接受答案。
                        
                    
                
            
        
            
        
                
                    
                
            
                
                    想改善这个问题吗?添加详细信息并通过editing this post阐明问题。
                
                    5年前关闭。
            
        

    

我想按键计算一个数组。并比较他们

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

最佳答案

如果您的目标是提高可读性,我建议您使用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))

09-04 15:49