最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to sort an array of objects by 'moment' date values? - Stack Overflow

programmeradmin2浏览0评论

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')))

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')))
Share Improve this question asked Jul 20, 2020 at 19:43 uberuber 5,0836 gold badges31 silver badges64 bronze badges 1
  • 1 Your sorting logic is backwards. For a boolean function to work in a sort, the false value has to mean that a goes before b, and true means that b goes before a. Here you return true if a goes before b. – James Commented Jul 20, 2020 at 19:50
Add a comment  | 

5 Answers 5

Reset to default 9

Use Moment's diff

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

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)

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)

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);

发布评论

评论列表(0)

  1. 暂无评论