JSON array of objects with properties and group it

For now, here is the code

const data = [ { "from":"03/01/2021", "to":"03/06/2021" }, { "from":"03/10/2021", "to":"03/15/2021" }, { "from":"03/20/2021", "to":"03/25/2021" } ]

const monthToString = month => {
  const months = {
    '01': 'Jan',
    '02': 'Feb',
    '03': 'Mar',
    '04': 'Apr',
    '05': 'May',
    '06': 'Jun',
    '07': 'Jul',
    '08': 'Aug',
    '09': 'Sep',
    '10': 'Oct',
    '11': 'Nov',
    '12': 'Dec',
    
  }
  return months[month] || month
}


const result = Object.entries(data.reduce((res, {from, to}) => {
  const [monthFrom, day, year] = from.split('/')
  const [m, dayTo, y] = to.split('/')
  
  const month = monthToString(m)
  
  return {
   ...res,
   [month]: [...(res[month] || []), [day, dayTo]]
  }
  
}, {})).map(([month, days]) => `${month} ${days.map(([from, to]) => `${parseInt(from)}-${parseInt(to)}`).join(', ')}`).join('\n')

console.log(result)

Can some help? Learning JS…little bit hard for me(

What do you have done so far? At which point exactly are you stuck?

const data = [ { "from":"03/01/2021", "to":"03/06/2021" }, { "from":"03/10/2021", "to":"03/15/2021" }, { "from":"03/20/2021", "to":"03/25/2021" } ]

const monthToString = month => {
  const months = {
    '01': 'Jan',
    '02': 'Feb',
    '03': 'Mar',
    '04': 'Apr',
    '05': 'May',
    '06': 'Jun',
    '07': 'Jul',
    '08': 'Aug',
    '09': 'Sep',
    '10': 'Oct',
    '11': 'Nov',
    '12': 'Dec',
    
  }
  return months[month] || month
}


const result = Object.entries(data.reduce((res, {from, to}) => {
  const [monthFrom, day, year] = from.split('/')
  const [m, dayTo, y] = to.split('/')
  
  const month = monthToString(m)
  
  return {
   ...res,
   [month]: [...(res[month] || []), [day, dayTo]]
  }
  
}, {})).map(([month, days]) => `${month} ${days.map(([from, to]) => `${parseInt(from)}-${parseInt(to)}`).join(', ')}`).join('\n')

console.log(result)

I dont know How to Combine dates when they intersect?

How would you do that by hand?

It is possible to compare the date “from” the first array with the second one, if it is greater than or equal to, we proceed to the comparison “to”

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.