Home > Mobile >  JS: Group array of time related objects by today, yesterday, last 7 days, and months
JS: Group array of time related objects by today, yesterday, last 7 days, and months

Time:01-30

I have the following case. Assuming I have an array like this:

const listOfObjects = [
  {
    title: "Title",
    date: "timestamp from today"
  },
  {
    title: "Title",
    date: "timestamp from yesterday"
  },
  {
    title: "Title",
    date: "timestamp from yesterday"
  },
  {
    title: "Title",
    date: "timestamp from one day in the last seven days"
  },
  {
    title: "Title",
    date: "timestamp from last month"
  },
  ...
]

My goal is to group these items in the following structure:

const structeredObjects = {
  "Today": [{
    title: "Title",
    date: "timestamp from today"
  }],
  "Yesterday": [{
    title: "Title",
    date: "timestamp from yesterday"
  },
  {
    title: "Title",
    date: "timestamp from yesterday"
  }],
  "Last seven days": [{
    title: "Title",
    date: "timestamp from one day in the last seven days"
  }],
  "January 2023": [{
    title: "Title",
    date: "timestamp"
  }],
  "December 2022": [{
    title: "Title",
    date: "timestamp"
  }],
  "November 2022": [{
    title: "Title",
    date: "timestamp"
  }],
  ...
}

I guess I can achieve this using Lodash's groupBy.

Grouping these items by month and year (like "January 2023", "December 2022", etc.) is working. But how should I go ahead when I want to have the extra keys "Today, Yesterday, Last seven days".

Thank you very much!

CodePudding user response:

Something like this might work if your timestamp is the Date object converted to string (you might need to adjust it's date format which you haven't mentioned because timestamps have different format. It's done inside the groupBy method where you check strings for equality)

const listOfObjects = [
  // Your objects here
];

const today = new Date();
const yesterday = new Date(today);
yesterday.setDate(yesterday.getDate() - 1);
const lastSevenDays = new Date(today);
lastSevenDays.setDate(lastSevenDays.getDate() - 7);

const structuredObjects = _.groupBy(listOfObjects, (item) => {
  const itemDate = new Date(item.date);
  if (itemDate.toDateString() === today.toDateString()) {
    return "Today";
  } else if (itemDate.toDateString() === yesterday.toDateString()) {
    return "Yesterday";
  } else if (itemDate > lastSevenDays) {
    return "Last seven days";
  } else {
    return `${itemDate.toLocaleString('default', { month: 'long' })} ${itemDate.getFullYear()}`;
  }
});
console.log(structuredObjects);
  • Related