JSFiddle - React, Tailwind, and code Playground
by lbstr
HTML
<script src="http://underscorejs.org/underscore-min.js"></script>
JavaScript
var datesIn = [
{ date: "12/15/2014", time: 80 },
{ date: "12/29/2014", time: 90 },
{ date: "12/22/2014", time: 10 },
{ date: "12/15/2014", time: 40 },
{ date: "12/22/2014", time: 30 },
{ date: "12/29/2014", time: 10 }
];
var datesOut = (function(dates) {
if (!dates) { return null; }
var joinedDates =
// Start a chaining context on our dates
_.chain(dates)
// Create a new object, which is the result of grouping each
// object in the dates array by their "date" property.
// This will return something like this:
// {
// "12/15/2014": [{...}, {...}],
// "12/29/2014": [{...}, {...}],
// "12/22/2014": [{...}, {...}]
// }
// The objects I've abbreviated with ... are the original
// objects from the date array (e.g. { date: "12/15/2014", time: 80 })
// So, basically we have an object whose keys are the unique
// dates and the values are the objects matching those dates.
.groupBy("date")
// The goal of this map routine is to reduce the values
// in the key-value-pairs described above.
// We'll reduce the values by summing their time properties.
// This will return something like this:
// [
// [ "12/15/2014": 120 ],
// [ "12/29/2014": 100 ],
// [ "12/22/2014": 40 ]
// ]
// In short, the arrays of grouped dates have been reduced to the
// sum of their "time" properties and we've returned
// things as arrays containing key-value-pairs.
.map(function(val, key) {
// val is something like this:
// [
// { date: "12/15/2014", time: 80 },
// { date: "12/15/2014", time: 40 }
// ]
// We want to reduce this array to the sum of the
// "time" values in each object.
var timeSum = _.reduce(
// val is...