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