I hate this array of objects, each object has a date, I want to be able to group these objects into months. Is there a way to convert this,
var data = [
{ date: "2016-08-13",...},
{ date: "2016-07-23",...},
{ date: "2016-08-11",...},
{ date: "2016-08-10",...},
{ date: "2016-07-20",...},
{ date: "2016-07-21",...},
]
into something like this
var data = [
[{ date: "2016-08-13",...},
{ date: "2016-08-11",...},
{ date: "2016-08-10",...}],
[{ date: "2016-07-20",...},
{ date: "2016-07-21",...},
{ date: "2016-07-23",...}[
]
You could take a part of the string for year and month group in a hash table and take for every group a new array and put this array to the result set.
var data = [{ date: "2016-08-13" }, { date: "2016-07-23" }, { date: "2016-08-11" }, { date: "2016-08-10" }, { date: "2016-07-20" }, { date: "2016-07-21" }],
hash = Object.create(null),
result = [];
data.forEach(function (o) {
var key = o.date.slice(0, 7);
if (!hash[key]) {
hash[key] = [];
result.push(hash[key]);
}
hash[key].push(o);
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With