linq.js to group by array of objects in javascript -
i want use linq.js group following data date.
data2 = [{ "date": 1399298400.0, "adid": 1057946139383, "impressions": 1000000 }, { "date": 1399298400.0, "adid": 3301784671323, "impressions": 535714 }...... etc. ];
here's attempt:
var linq = enumerable.from(data2); data2 = linq.groupby(function (x) { return x.date; }).select(function (x) { return { date: x.key(), impressions: x.sum(function (y) { return y.impressions | 0; }) }; }).toarray();
however, it's not working correctly because sum of impressions
before , after groupby
close not identical.
what correct way use group in linq.js in case?
here's an example in fiddle full dataset here alerts total impressions before , after using groupby
.
in order access key
property of groupby
, have within group method.
you can passing callback third parameter this:
var aggregatedobject = enumerable.from(dataarray) .groupby("$.date", null, function (key, g) { return { date: key, impressions: g.sum("$.impressions | 0") } }) .toarray();
the | 0
part of equation way of sanitizing data. in sample below, 1 of data array elements accidentally doesn't have impressions property. when javascript goes sum items in group, it'll chug along until encounters missing value, @ point result of entire aggregattion dreaded nan
:
what pipe (|
) operator in js return first value if exists, otherwise returns second one. expression safeguards against missing properties.
working demo stack snippets:
var dataarray = [{ "date": 1396828800, "impressions": 100 }, { "date": 1396828800, "impressions": 250 }, { "date": 1397001600, "impressions": 300 }, { "date": 1397001600 //,"impressions": 450 }]; var aggregatedobject = enumerable.from(dataarray) .groupby("$.date", null, function (key, g) { return { date: key, impressions: g.sum("$.impressions | 0") } }) .toarray(); console.table(aggregatedobject);
<script src="//cdnjs.cloudflare.com/ajax/libs/linq.js/2.2.0.2/linq.min.js"></script>
note: makes use of shorthand syntax, if prefer anytime see string dollar sign, can replace lambda syntax (the both same exact thing):
// lambda .select(function (x) { return x.impressions }) // shorthand .select("$.impressions")
also, can find more info on linqjs group sum
Comments
Post a Comment