简体   繁体   中英

how to do sorting in moment.js by newest and oldest?

my array is like this:

const myArr = [{text: 'Hello', created: '2018-05-22T08:56:42.491Z'}, {text: 'Hello', created: '2018-05-24T05:56:42.491Z'},]

with this kind of array, I want to sort them by newest and oldest, this is my current implementation which does not work:

if (sortFilter === 'oldest') {
      contactData = contactData.sort(({ created: prev }, { created: next }) => moment(prev).format('L') - moment(next).format('L'));
    } else if (sortFilter === 'newest') {
      contactData = contactData.sort(({ created: prev }, { created: next }) => moment(next).format('L') - moment(prev).format('L'));
    }

what's wrong with my code?

You have ISO 8601 date string which is built to sort lexicographically.

 let myArr = [{text: 'Hello', created: '2018-05-22T08:56:42.491Z'}, {text: 'Hello', created: '2018-05-24T05:56:42.491Z'}]; myArr.sort((a,b) => a.created.localeCompare(b.created)); console.log(myArr); 

Without using momentjs, you can use sort() and use new Date() and convert string to date object.

Newest first.

 const myArr = [{ text: 'Hello', created: '2018-05-22T08:56:42.491Z' }, { text: 'Hello', created: '2018-05-24T05:56:42.491Z' }, ]; myArr.sort((a,b)=> new Date(b.created).getTime() - new Date(a.created).getTime()); console.log(myArr); 

Oldest First:

 const myArr = [{ text: 'Hello', created: '2018-05-22T08:56:42.491Z' }, { text: 'Hello', created: '2018-05-24T05:56:42.491Z' }, ]; myArr.sort((a, b) => new Date(a.created).getTime() - new Date(b.created).getTime()); console.log(myArr); 

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