How to distribute objects into arrays depending on their date?

Issue

I ran into a problem that I don’t know how to distribute objects based on their date. I would be very grateful for your help!

const arr = [
    { obj: 1, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 2, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 3, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 4, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 5, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 6, date: {day: '14', month: 'Oct', year: '2023'} },
];

The expected output:

[
  [
    { obj: 1, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 3, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 4, date: {day: '9', month: 'Oct', year: '2022'} },
  ],
  [
    { obj: 2, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 5, date: {day: '9', month: 'Jan', year: '2022'} },
  ],
  [
    { obj: 6, date: {day: '14', month: 'Oct', year: '2023'} },
  ],
];

Solution

You could use the date as an identifier to find the matches using Object.values() in a reduce iterator

const arr = [
    { obj: 1, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 2, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 3, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 4, date: {day: '9', month: 'Oct', year: '2022'} },
    { obj: 5, date: {day: '9', month: 'Jan', year: '2022'} },
    { obj: 6, date: {day: '14', month: 'Oct', year: '2023'} },
];

let sorted = Object.values(arr.reduce((b, a) => {
  let val = Object.values(a.date).join('') // create the date identifier
  if (!b[val]) b[val] = []; // if we haven't used it yet, create it
  b[val].push(a); // add the object
  return b;
}, {}))

console.log(sorted)

Answered By – Kinglish

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published