How can I optimize my array filtering by date times?

Viewed 37

I wrote this simple filter array per data time, but not sure if it's good way.

Example data:

[
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]

And i want to convert it like this:

 {
      "Fri May 29 2020": [
        {
          "content": "test1",
          "createdAt": "2020-05-29T13:46:14.000Z"
        },
        {
          "content": "test2",
          "createdAt": "2020-05-29T13:46:14.000Z"
        }
      ],
      "Wed May 27 2020": [
        {
          "content": "test3",
          "createdAt": "2020-05-27T13:46:14.000Z"
        }
      ]
    }

And there is my code:

let usedDates = new Set();
let logs = {};

for(let log of data) {
    const date = new Date(log.createdAt).toDateString();
    if(usedDates.has(date)) continue;

    logs[date] = data.filter((e) => date == new Date(e.createdAt).toDateString());
    usedDates.add(date);
}

yeah it works, but not sure if it's good way.

2 Answers

This one simple reduce trick can help you

const data = [
  {
    "content": "test1",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test2",
    "createdAt": "2020-05-29T13:46:14.000Z"
  },
  {
    "content": "test3",
    "createdAt": "2020-05-27T13:46:14.000Z"
  }
]

const result = data.reduce((acc, value) => {
  const date = new Date(value.createdAt);
  const dateFormatted = date.toDateString();
  
  acc[dateFormatted] = [...(acc[dateFormatted] || []), value];
  
  return acc;

}, {})

console.log(result);

For big arrays it hasn't a good performance: you walk throw data array (for loop) and for each step you call a filter on the full data. The costs rise to the square.

Related