简体   繁体   English

Javascript 对象数组排序

[英]Javascript Array of Objects Sort

This is my array.这是我的阵列。 i am trying to sort it with the date value.我正在尝试使用日期值对其进行排序。

var dates = [{date: Sat Mar 06 2021}, {date: Fri Mar 05 2021}, {date:Sun Mar 07 2021}]

i have tried this but it is not working for me我已经尝试过了,但它不适合我

let sortedDates = dates.sort((a, b) => new Date(...a.date.split('/').reverse()) - new Date(...b.date.split('/').reverse()));

 const activities = [{date: 'Sat Mar 06 2021'}, {date: 'Fri Mar 05 2021'}, {date:'Sun Mar 07 2021'}] const sortedActivities = activities.sort((a, b) => new Date(a.date) - new Date(b.date)); console.log(sortedActivities);

You can try this.你可以试试这个。 It will work for you.它会为你工作。

You are doing few things wrong.你做错了几件事。 First, your "dates" in array will crash your code, since they should be strings.首先,数组中的“日期”会使您的代码崩溃,因为它们应该是字符串。 Then you are trying to split it with / , but there is no such character.然后你试图用/分割它,但没有这样的字符。 You want to split them with a space.您想用空格分隔它们。 Ideally, you should always keep your data in machine readable format - unix time in milliseconds, IETF-compliant RFC 2822 timestamps or ISO 8601 (they might have different effect in JS, so read about Date ).理想情况下,您应该始终以机器可读格式保存数据 - unix 时间(以毫秒为单位)、符合 IETF 的 RFC 2822 时间戳或 ISO 8601(它们在 JS 中可能具有不同的效果,因此请阅读Date )。

As for your current case, your thoughts, in general, are correct, but your execution is wrong.至于你现在的情况,总体来说你的想法是对的,但是你的执行是错误的。 First you want to split your string by space: let arr = date.split(' ') .首先你想用空格分割你的字符串: let arr = date.split(' ') Then you want to separate it in parts and then assemble said parts in a way that Date.parse function would understand:然后你想将它分成几部分,然后以Date.parse function 可以理解的方式组装所述部分:

let [dayOfWeek, month, day, year] = date.split(" ");
let dateInMilliseconds = Date.parse(`${day} ${month} ${year}`);

And now you can compate your dates.现在你可以比较你的日期了。

To put it all together you will get this:把它们放在一起,你会得到这个:

function parseDate(date) {
  let [dayOfWeek, month, day, year] = date.split(" ");
  return Date.parse(`${day} ${month} ${year}`);
}

let dates = [
  { date: "Sat Mar 06 2021" },
  { date: "Fri Mar 05 2021" },
  { date: "Sun Mar 07 2021" },
];

let sortedDates = dates.sort((a, b) => parseDate(a.date) - parseDate(b.date));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM