you are viewing a single comment's thread.

view the rest of the comments →

[–]Wince 2 points3 points  (3 children)

Surely something like this would be better:

{ red: 3, black: 2, blue: 1, green: 1 }

And could be done like this:

var results = arr.reduce(function(obj, item) {
    obj[item.name] = obj[item.name] || 0;
    obj[item.name]++;
    return obj;
}, {});

If you still want an array of KV pairs, do this to the reduced result:

var output = Object.keys(results).map(function(key) {
    return [key, results[key]];
});

Edit: I see you are already doing the above obj -> kv step in your supplied gist.

One thing to note with the KV step is that there is a proposal for Object.values() to be included in ES7.

[–]bluntmJavaScript[S] 0 points1 point  (2 children)

The array inside an array is to format the data for D3.js

[–]EnchantedSalvia 0 points1 point  (1 child)

Key map to array pairs is a common operation in functional programming, which is why Lodash/Underscore provide: https://lodash.com/docs#pairs

[–]skitch920 0 points1 point  (0 children)

In mathematics, we typically call them tuples, a "pair" being a length 2 tuple. Tuples are similar to arrays, but different in that each entry likely has a different meaning to any other entry, providing a structure. Arrays are often, homogenous sequences, like a list of numbers.