Home > front end >  Is there a way to compare dates and store them in an array?
Is there a way to compare dates and store them in an array?

Time:10-14

I'm currently working on a website where Objects are sorted. The Objects are from a database where it's stored with a date (2022-10-13 02:07:11). Is there a way to compare dates and store the ones that are created on the same date? For example: If there are two objects that were created on 2022-10-13, but with at a different time, I would like to save these in an array with the name of the date. I can't change how it's saved because it's not my DB.

I hope you understand how I mean it.

CodePudding user response:

(I don't know how you want it or how your database is exactly so you might have to change some things)

Try using (something like) this:

let sorted = {};
// replace "data" below with your key
for(key in data){
    if(!sorted[data[key].date]){
        sorted[data[key].date] = [];
    }

    sorted[data[key].date].push({key: data[key]});
}

Example in my case:

let data = {
  "a": {
    "date": "2022-10-13 02:07:11"
  },
  "b": {
    "date": "2022-10-13 00:00:00"
  },
  "c": {
    "date": "2022-10-10 02:07:11"
  }
};

let sorted = {};

for (key in data) {
  if (!sorted[data[key].date]) {
    sorted[data[key].date] = [];
  }

  sorted[data[key].date].push({
    key: data[key]
  });
}

console.log(sorted);

CodePudding user response:

A reduce is useful here

Give us more details of the object to give a more tailored answer

const obj = [
{ "id": "a1", "date": "2022-10-13 01:07:11" },
{ "id": "a2", "date": "2022-10-13 02:07:11" },
{ "id": "a3", "date": "2022-10-13 03:07:11" },
{ "id": "b",  "date": "2022-10-14 02:07:11" },
{ "id": "c1", "date": "2022-10-15 01:07:11" },
{ "id": "c2", "date": "2022-10-15 02:07:11" },
{ "id": "c3", "date": "2022-10-15 03:07:11" },
{ "id": "d",  "date": "2022-10-16 01:07:11" }
];
const grouped = obj.reduce((acc,cur) => {
  const key = cur.date.split(" ")[0];
  (acc[key] = acc[key] || []).push(cur);
  return acc;
},{})
console.log(grouped);

  • Related