Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
671 views
in Technique[技术] by (71.8m points)

javascript - Split array of objects into new arrays based on year of object's date

I have an array of objects called objarray. Each object looks like this:

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 within dateGroups contains objects with the same date.

Is this possible to do with arrays? Previously I generated a new object which contained all the objarray objects grouped by date (dates generated from the data):

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

The above seems like a weird solution in practice though, I only need to be able to access the objects by year: i.e. dateGroups[0] = array of objects from the first year

How would I get the data into something like the dateGroups array? Is there a better way to store this type of data?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

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

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

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

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

You can also combine 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 case, I can see reasons for using an array of arrays, or an object map of arrays. If you're looking up on index, definitely use the later.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...