简体   繁体   中英

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. 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??? *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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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