简体   繁体   中英

Sort by array of objects by newest date does not work

I need to sort dates by newest.

This is sortByDate() function - this sorting list currently will sort date by oldest date instead of newest.

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

And this is newsList which need to be sorted:

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'
    }
]

Currently sortByDate sort my data by oldest date, why he does not work as expected?

This should do what you need, sorting with the newest first. You could also pass a sortorder parameter to the sorting function to indicate the sort order you require.

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

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