What is the best way to group objects by date and add them all up to create a single JavaScript object? I prefer code readability and lesser lines of code over performance as the application is not data intensive. Moreover there are going to be lots people who are going to make changes after I'm done with my internship.
Here is some sample data
[
{"Timestamp":"Thu, 01 Jan 2015 00:57:00 GMT","cp":2,"pc":2},
{"Timestamp":"Thu, 01 Jan 2015 01:57:00 GMT","cp":0,"pc":4},
{"Timestamp":"Thu, 01 Jan 2015 02:57:00 GMT","cp":2,"pc":2},
{"Timestamp":"Thu, 01 Jan 2015 03:57:00 GMT","cp":0,"pc":4},
{"Timestamp":"Thu, 02 Jan 2015 00:57:00 GMT","cp":2,"pc":2},
{"Timestamp":"Thu, 02 Jan 2015 01:57:00 GMT","cp":0,"pc":4},
{"Timestamp":"Thu, 02 Jan 2015 02:57:00 GMT","cp":2,"pc":2},
{"Timestamp":"Thu, 02 Jan 2015 03:57:00 GMT","cp":0,"pc":4}
]
I want to create this out of the above data.
[ {"Date":"2015-01-01", "cp":4, "pc":12}, {"Date":"2015-01-02", "cp":4, "pc"12} ]
If you notice, the resultant JavaScript object is the sum total of all the columns on that particular date and replace timestamp by date.
We already use moment.js in the application, so I have it at disposal. If you think moment can solve the problem in a neater fashion, please let me know.
Try this.
$.each()
function can be used to iterate over any collection.)UTC
format date string toISO
format usingtoISOString()
method.indexOf()
method.Here is the Code:
Hope this may helpful for you.
I believe a simple utility library such as Underscore.js or Lodash could do the job, however, this looks like a task plain old vanilla Javascript can take on by itself.
Check out the Array.prototype.map function, or probably better yet an Array.prototype.sort that takes in a sorting function applying logic to a given object's
.Timestamp
property.Edit: something like
may work.
EDIT: I see now you are trying to merge dates. In that case, I would say
Array.prototype.map
chained withArray.prototype.reduce
is a possible path to go down. You could also (messily) useArray.prototype.filter
to push all arrays of a given date into a single array, and so on for each date.Edit:
How about a reduce, then?