开发者

sort JSON by date

I know this must be 开发者_如何学Gorelatively 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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜