Counting duration values I have a durations as such:

[{'duration': 3600}, {'duration': 3600}]


And I want the output to be {3600: 2}, where 2 is the number of occurrences of 3600.

My first attempt is use a loop, as such:

    var count = {};
    for (var d of durations) {
        var length = d.duration;
        if (length in count) {
            count[length] += 1;
        }
        else {
            count[length] = 1;
        }
    }
    console.log(count);


The second attempt uses reduce() in lodash:

    function foo(result, value) {
        var length = value.duration;

        if (length in result) {
            result[length] += 1;
        }
        else {
            result[length] = 1;
        }

        return result;
    }
    var reduced = _.reduce(durations, foo, {});
    console.log(reduced);


As can be seen, this second attempt is still as verbose as before.

Is there a way to write the iteratee function foo more conform to functional programming?
It's not really clear what you mean by "functional".

The use of reduce is nifty, and correctly done, but it seem like cargo cult programming. The realization that a lot of loop-like actions can be represented in terms of reduce (fold, aggregate, etc) is important to functional programing, but it should no more be your first choice than a while-loop.

The fact that it's verbose isn't necessarily a problem. It suggests that you might be failing at a general goal:


  Write what you mean.


One of the things that makes functional programming good is that it helps us do that.
Javascript has limited tools for directly declaring lists. What you mean to do is declare a Dictionary from the Set of duration values to the Count of the source array Filtered by the respective duration. Or even better you could use a grouping function.

You could bring in a library for the task, which may be a good idea, or you could compromise a little.

function getCounts(items, key){
  let c = {};
  for(let item of items){
    c[key(item)] = items.filter(function(i){
        return key(i) === key(item);
      }).length;
  }
  return c;
};
counts = getCounts(durations, function(i){ return i['duration']; })'


You'll notice that that's quite inefficient. We could make it less wasteful, but it'd be less terse.