0

Edit: Found the answer from a duplicate threat. Please ignore this, thank you

I've been struggling to sort an array of object below. The goal is to iterate over and display the images in the object, but they need to be separated by the dates in order.

So for example, the order to display should be:

July 12, 2001

  • image
  • image
  • image

January 1, 2000

  • image
  • image
  • image

October 10, 1999

  • image
  • image
  • image

The issue is a sorting issue for me. I can iterate and display all the images, but the images are not being sorted via their dates.

arr: [
  {
    date: 'January 1, 2000',
    url: 'string',
    id: 1
  },
  {
    date: 'July 12, 2001',
    url: 'string',
    id: 142
  },
  {
    date: 'October 10, 1999',
    url: 'string',
    id: 333
  },
  {
    date: 'January 12, 2000',
    url: 'string',
    id: 1
  },
  {
    date: 'January 1, 2000',
    url: 'string',
    id: 1
  },
  {
    date: 'July 12, 2001',
    url: 'string',
    id: 142
  },
  {
    date: 'October 10, 1999',
    url: 'string',
    id: 333
  },
  {
    date: 'July 12, 2001',
    url: 'string',
    id: 142
  },
  {
    date: 'October 10, 1999',
    url: 'string',
    id: 333
  },
]

I've tried using lodash libray function _.keyBy and returns me 3 objects with the date as the key and the value as the object associated with said key, however, it only returns one object per key not all objects assoicated with the date.

Edit: Sorting by ID will also work, but i'll still need to display the title as the date which shouldn't be an issue

Generaldeep
  • 437
  • 2
  • 12
  • 30

1 Answers1

-1

At first you have to group the images by date:

const day = {}, result = [];

for(const {date, ...img} of arr) {
  if(day[date]) {
    day[date].push(img);
  } else {
    result.push({date, entries: (day[date] = [img]) });
 }
}

Then you can just sort the result by date:

result.sort((a, b) => +new Date(a.date) - new Date(b.date));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • 1
    `parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies.` - MDN – Matus Dubrava Jun 13 '18 at 12:48