按日期排序JSON [英] sort JSON by date
问题描述
我知道这必须相对简单,但我有一个JSON数据集,我希望按日期排序。到目前为止,我每次都遇到问题。
现在我将日期存储为 this.lastUpdated
。
如果有帮助我可以访问jquery,但我知道.sort()是本机JS。
提前致谢。
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.
推荐答案
假设您有一个javascript对象数组,只需使用自定义排序功能:
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);
Array sort
方法使用数组排序一个回调函数,它传递数组中的元素对。
The Array sort
method sorts an array using a callback function that is passed pairs of elements in the array.
- 如果返回值为负,则第一个参数(
a
在这种情况下),将在排序数组中的第二个参数(b
)之前。 - 如果返回值为零,则它们相对于彼此的位置保持不变。
- 如果返回值为正,
b
在排序后的a
之前数组。
- 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
precedesa
in the sorted array.
您可以在 sort
方法上阅读更多信息此处。
You can read more on the sort
method here.
这篇关于按日期排序JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!