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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 06:23:21  来源:igfitidea点击:

sort JSON by date

javascriptjqueryjson

提问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 sortmethod 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 (ain 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, bprecedes ain the sorted array.
  • 如果返回值为负,则第一个参数(a在本例中)将在b排序数组中的第二个参数 ( )之前。
  • 如果返回值为零,则它们相对于彼此的位置保持不变。
  • 如果返回值是正数,则排在已排序数组的b前面a

You can read more on the sortmethod here.

您可以在此处阅读有关该sort方法的更多信息