Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Group array of objects by string property value in JavaScript?

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",...}[
]
like image 404
relidon Avatar asked Oct 27 '25 03:10

relidon


1 Answers

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; }
like image 66
Nina Scholz Avatar answered Oct 28 '25 18:10

Nina Scholz