[ACCEPTED]-Split array of objects into new arrays based on year of object's date-grouping

Accepted answer
Score: 10

Consider using the Underscore.js groupBy function, followed 8 by sortBy.

groupBy will produce a structure like alldates, if 7 you call it like so:

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

sortBy can be used to simply 6 sort by key, like this:

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

You can also combine 5 the two like this:

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

Depending on your use 4 case, I can see reasons for using an array 3 of arrays, or an object map of arrays. If 2 you're looking up on index, definitely use 1 the later.

Score: 2

An answer using reduce.

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 reduce 5 is for grouping the objects by dates, and 4 the second is for making the key of the 3 array run from 0 to the number of different 2 years - instead of the key being the year 1 itself.

More Related questions