0

I'd like to count by key for an array. and diff the count them

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));

Expected Output

Object {1: 1, 2: -1, 3: 1} // first - second
Object {1: -1, 2: 1}       // second - first
freddiefujiwara
  • 57,041
  • 28
  • 76
  • 106

1 Answers1

1

If your goal is to improve readability i would suggest using underscorejs (http://underscorejs.org/).

Here's how you can do it with 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))
Furqan Zafar
  • 1,471
  • 1
  • 13
  • 17