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
289 views
in Technique[技术] by (71.8m points)

javascript - sort JSON by date

I know this must be relatively simple, but I have a dataset of JSON that I would like to sort by date. So far, I've run into problems at every turn. Right now I have the date stored as this.lastUpdated. I have access to jquery if that helps, but I realize the .sort() is native JS. Thanks in advance.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Assuming that you have an array of javascript objects, just use a custom sort function:

function custom_sort(a, b) {
    return new Date(a.lastUpdated).getTime() - new Date(b.lastUpdated).getTime();
}
var your_array = [
    {lastUpdated: "2010/01/01"},
    {lastUpdated: "2009/01/01"},
    {lastUpdated: "2010/07/01"}
];

your_array.sort(custom_sort);

The Array sort method sorts an array using a callback function that is passed pairs of elements in the array.

  • If the return value is negative, the first argument (a in this case), will precede the second argument (b) in the sorted array.
  • If the returned value is zero, their position with respect to each other remains unchanged.
  • If the returned value is positive, b precedes a in the sorted array.

You can read more on the sort method here.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
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

...