Ian Warner Ian Warner - 22 days ago 12
Javascript Question

Lodash or JS GroupBy and Count for array of arrays

I have a input :

results = [
[ "Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS1", "small", "SW192EZ", "undefined" ],
[ "Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS2", "large", "SW192EZ", "undefined" ],
[ "Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS2", "large", "SW192EZ", "undefined" ],
[ "Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS2", "medium", "SW192EZ", "undefined" ],
]


I want the output to be something like

small
DryKISS1 : 1
medium
DryKISS2 : 1
large
DryKISS1 : 5
DryKISS2 : 2
DryKISS3 : 8


Basically grouping by size and then summing a company name in the same size bracket.

I have been playing with the below, but get lost as most of the examples are for hashes / objects

console.log _.chain( results ).groupBy( 4 ).map( ( value, key ) ->
[
key
_.reduce( value, ( ( result, currentObject ) ->
{
company: result[ 3 ]
}
))
]
).value()


Any help appreciated

Answer

In plain Javascript, you could use an object with nested properties for the count.

var results = [["Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS1", "small", "SW192EZ", "undefined"], ["Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS2", "large", "SW192EZ", "undefined"], ["Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS2", "large", "SW192EZ", "undefined"], ["Mon Nov 14 08:08:14 GMT+07:00 2016", "Ian Warner", "ian.warner@drykiss.com", "DryKISS2", "medium", "SW192EZ", "undefined"]],
    grouped = {};

results.forEach(function (a) {
    grouped[a[4]] = grouped[a[4]] || {};
    grouped[a[4]][a[3]] = (grouped[a[4]][a[3]] || 0) + 1;
});

console.log(grouped);