简体   繁体   English

如何将日期表单排序为对象数组中最新到最旧的反应js

[英]How to sort the date form to latest to the oldest in array of objects react js

im trying to sort the date from this array of objects from the latest to the oldest.我试图从最新到最旧的对象数组中对日期进行排序。 Im trying this code, copying the array to a new const then using it with sort, but I have the same result, no sorted date.我正在尝试这段代码,将数组复制到一个新的 const 然后将它与排序一起使用,但我有相同的结果,没有排序日期。 My code is below:我的代码如下:

const array=[...user?.editedBy]
console.log(array,"array")

const sortedDates = array?.sort((dateA, dateB) => dateB.date -dateA.date )
console.log(sortedDates,'sortedArray')

The first pic its the console log from array and the second from sortedDates, So the same result, can someone please help me figure it out what Im missing???第一张图片是来自数组的控制台日志,第二张来自 sortedDates,所以结果相同,有人可以帮我弄清楚我错过了什么吗??? *Thank you in advance * *先感谢您 *

在此处输入图像描述 在此处输入图像描述

As you can see in your console screenshot, this isn't a Date array, but a string array.正如您在控制台屏幕截图中看到的,这不是一个日期数组,而是一个字符串数组。

So you have to map the strings to Date objects and compare them afterward.因此,您必须将字符串 map 转换为Date对象,然后再进行比较。

const sortedDates = array?
  .map(dateString => new Date(dateString))
  .sort((dateA, dateB) => dateB.date - dateA.date)

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

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