James Delaney
James Delaney

Reputation: 1776

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?

Upvotes: 0

Views: 74

Answers (1)

Terry Lennox
Terry Lennox

Reputation: 30685

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

Upvotes: 2

Related Questions