Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 927
gpbaculio Avatar asked Sep 12 '25 18:09

gpbaculio


1 Answers

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);
like image 114
Eddie Avatar answered Sep 15 '25 08:09

Eddie