Split an array of objects into new arrays depending on the year of the date of the object

I have an array of objects called objarray . Each object is as follows:

var object = {
    age: "45"
    coords: "-37.807997 144.705784"
    date: Sun Jul 28 2002 00:00:00 GMT+1000 (EST)
}

( date is a Date object)

I need to push each object into a new array based on the date. I want the end result to look like this:

var dateGroups = [[object, object, object],[object, object], [object, object, object]];

Each array in dateGroups contains objects with the same date.

Is this possible with arrays? Earlier, I generated a new object containing all objarray objects grouped by date (dates generated from data):

var alldates = {
  "1991" : [object, object, object],
  "1992" : [object, object],
  //etc...
}

, : ie dateGroups [0]=

dateGroups? ?

+5
3

Underscore.js groupBy, sortBy.

groupBy ​​, alldates, :

var alldates = _.groupBy(objarray, function(obj) {
    return obj.date.getFullYear();
});

sortBy , :

var dateGroups = _.sortBy(alldates, function(v, k) { return k; });

:

var dateGroups = _.chain(objarray)
                  .groupBy(function(obj) { return obj.date.getFullYear(); })
                  .sortBy(function(v, k) { return k; })
                  .value();

. , .

+7

, :

var alldates = {
  "1991" : [object, object, object],
  "1992" : [object, object],
  //etc...
}

, :

var dateGroups = [];

for(var year in allDates){
   dateGroups[dateGroups.length] = allDates[year];
}
0

Answer using abbreviation.

var ans = objects.reduce(function(prev,curr) {
    if (!prev[curr.date.getFullYear()]) prev[curr.date.getFullYear()] = [];
    prev[curr.date.getFullYear()] = curr;
    return prev;
},[]).reduce(function(prev,curr) {
    prev.push(curr);
    return prev;
},[]);

the first abbreviation is for grouping objects by dates, and the second is for the key from the array to work from 0 to the number of different years - instead of the key being the year itself.

0
source

All Articles