Javascript 按日期对 JSON 进行排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3859239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
sort JSON by date
提问by Munzilla
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.
我知道这一定相对简单,但我有一个 JSON 数据集,我想按日期排序。到目前为止,我每次都遇到问题。现在我将日期存储为this.lastUpdated
. 如果有帮助,我可以访问 jquery,但我意识到 .sort() 是原生 JS。提前致谢。
回答by Sean Vieira
Assuming that you have an array of javascript objects, just use a custom sort function:
假设您有一组 javascript 对象,只需使用自定义排序函数:
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.
Arraysort
方法使用传递数组中元素对的回调函数对数组进行排序。
- 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.
- 如果返回值为负,则第一个参数(
a
在本例中)将在b
排序数组中的第二个参数 ( )之前。 - 如果返回值为零,则它们相对于彼此的位置保持不变。
- 如果返回值是正数,则排在已排序数组的
b
前面a
。
You can read more on the sort
method here.