我的数组是这样的:
const myArr = [{text: 'Hello', created: '2018-05-22T08:56:42.491Z'}, {text: 'Hello', created: '2018-05-24T05:56:42.491Z'},]
使用这种数组,我想按最新和最旧的方式对它们进行排序,这是我当前的实现,它不起作用:
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'));
}
我的代码出了什么问题?
答案 0 :(得分:3)
不使用momentjs,您可以使用sort()
并使用new Date()
并将字符串转换为日期对象。
最新的。
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);
最早的第一个:
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);
答案 1 :(得分:3)
您有ISO 8601日期字符串,用于按字典顺序排序。
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);