简体   繁体   中英

How to sort an array of objects by 'moment' date values?

The array consists of objects like these

[
  {
    name: 'john',
    date: '21-07-2020',
    car: 'bmw'
  },
  {
    name: 'fred',
    date: '14-10-2020',
    car: 'tesla'
  }
]

I am trying to sort it in ascending order using Moment's isBefore function but it isn't working, using Moment library:

array.sort((a, b) => moment(a.date, 'DD-MM-YYYY').isBefore(moment(b.date, 'DD-MM-YYYY')))

You can just do a simple subtraction and use Array#sort .

const dateArray = ['14-10-2020', '21-07-2020']
dateArray.sort((a,b) => new Moment(a).format('DD-MM-YYYY') - new Moment(b).format('DD-MM-YYYY'))
console.log(mySortedArray)

The issue because isBefore() return boolean and the sort callback expect number so you need to map this value.

// ascending
array.sort((a, b) =>
    moment(a.date, 'DD-MM-YYYY').isBefore(moment(b.date, 'DD-MM-YYYY')) ? -1 : 1,
)

// descending
array.sort((a, b) =>
    moment(a.date, 'DD-MM-YYYY').isBefore(moment(b.date, 'DD-MM-YYYY')) ? 1 : -1,
)


Also you can do it without moment with Date.parse() .

const getMS = date => {
  const d = date[0] + date[1];
  const m = date[3] + date[4];
  const y = date[6] + date[7] + date[8] + date[9];
  return Date.parse(`${y}-${m}-${d}`);
};


const arr = [
  {
    name: 'john',
    date: '21-07-2020',
    car: 'bmw',
  },
  {
    name: 'fred',
    date: '14-10-2020',
    car: 'tesla',
  },
];

// ascending
const sortedArr = arr.sort((a, b) => getMS(a.date) - getMS(b.date));

// descending
// const sortedArr = arr.sort((a, b) => getMS(b.date) - getMS(a.date));

console.log(sortedArr)

To sort using "moment"

function sortDate(dateA, dateB, direction = 'asc') {
    const formats = ['DD-MM-YYYY']; // can be several
    return (moment(dateA, formats).isBefore(moment(dateB, formats)) ? -1
        : moment(dateA, formats).isAfter(moment(dateB, formats)) ? 1 : 0) * (direction === 'asc' ? 1 : -1)
}

Example:

const array = [
    {
        name: 'john',
        date: '21-07-2020',
        car: 'bmw'
    },
    {
        name: 'fred',
        date: '14-10-2020',
        car: 'tesla'
    },
    {
        name: 'bed',
        date: '15-10-2020',
        car: 'ferrari'
    },
    {
        name: 'j',
        date: '12-10-2020',
        car: 'rolls royce'
    }
];

array.sort((a, b) => sortDate(a.date, b.date)); // sort ascending
array.sort((a, b) => sortDate(a.date, b.date, 'desc')); // sort descending

There's no need to convert the string to a moment to sort it.

arr.sort(({date:date1},{date:date2})=>
      date1.split("-").reverse().join('')
        .localeCompare(
              date2.split("-").reverse().join('')));

 const arr = [ { name: 'john', date: '21-07-2020', car: 'bmw' }, { name: 'fred', date: '14-10-2020', car: 'tesla' } ]; arr.sort(({date:date1},{date:date2})=>date1.split("-").reverse().join('').localeCompare(date2.split("-").reverse().join(''))); console.log(arr);

Use Moment's diff

array.sort((a, b) => moment(a.date, 'DD-MM-YYYY').diff(moment(b.date, 'DD-MM-YYYY')))

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