我需要按最新日期排序。
这是sortByDate()
函数-当前此排序列表将按最早的日期而不是最新的日期对日期进行排序。
sortByDate = () => {
const { newsList } = this.state;
newsList.sort((a, b) => {
const c = new Date(a.date);
const d = new Date(b.date);
return c - d;
});
this.setState({ newsList });
};
这是新闻列表,需要对其进行排序:
hits: [
{
id: '14253463',
doc_type: 'doc-test-type',
lang: 'eng',
author_name: 'Matt Davis',
author_id: 'BBC Sport',
date: '11 June 2019'
},
{
id: '14253463',
doc_type: 'doc-test-type',
lang: 'eng',
author_name: 'Matt Davis',
author_id: 'BBC Sport',
date: '10 June 2019'
},
{
id: '14253463',
doc_type: 'doc-test-type',
lang: 'eng',
author_name: 'Matt Davis',
author_id: 'BBC Sport',
date: '29 June 2019'
}
]
当前sortByDate
按最早的日期对我的数据进行排序,为什么他不能按预期工作?
答案 0 :(得分:2)
这应该做您需要的事情,以最新的为准。您还可以将sortorder参数传递给sorting函数,以指示所需的排序顺序。
newsList = [ { id: '14253463', doc_type: 'doc-test-type', lang: 'eng', author_name: 'Matt Davis', author_id: 'BBC Sport', date: '11 June 2019' }, { id: '14253463', doc_type: 'doc-test-type', lang: 'eng', author_name: 'Matt Davis', author_id: 'BBC Sport', date: '10 June 2019' }, { id: '14253463', doc_type: 'doc-test-type', lang: 'eng', author_name: 'Matt Davis', author_id: 'BBC Sport', date: '29 June 2019' }];
console.log("Original list: ");
newsList.forEach(h => console.log(new Date(h.date).toLocaleDateString()));
newsList.sort((a, b) => {
const c = new Date(a.date);
const d = new Date(b.date);
return d - c;
});
console.log("Sorted list: ");
newsList.forEach(h => console.log(new Date(h.date).toLocaleDateString()));