Search code examples
javascriptmomentjslodash

how to make the empty value for the day using moment


I want to plot the data for the week in bar chart, how to give the empty value if the date is not there in the response object. I am using moment and lodash groupby for the find which day for the week.

const actionHistory = [
    {
      "c_code": "FIELD_VISIT",
      "amtp_actionTaken": "call",
      "amtp_takenOn": "2023-01-13T18:28:12.850Z"
    },
    {
      "c_code": "FIELD_VISIT",
      "amtp_actionTaken": "call",
      "amtp_takenOn": "2023-01-11T18:28:12.850Z"
    }
  ];
const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
const month = groupBy(actionHistory, (dt) => moment(dt?.amtp_takenOn).days());
const result = map(month, (el, i) => ({ value: el?.length, label: weekdays[i - 1], frontColor: '#177AD5' });`

if i put console.log to result I getting the only the aviable date week days like this

[{"value":1,"label":"Tue","frontColor":"#177AD5"},{"value":1,"label":"Thu","frontColor":"#177AD5"}]

my expected output should be.

[{"value":0,"label":"Sun","frontColor":"#177AD5"}, 
 {"value":0,"label":"Mon","frontColor":"#177AD5"}, 
 {"value":1,"label":"Tue","frontColor":"#177AD5"}, 
 {"value":1,"label":"Wed","frontColor":"#177AD5"}, 
 {"value":1,"label":"Thu","frontColor":"#177AD5"}, 
 {"value":0,"label":"Fir","frontColor":"#177AD5"},
 {"value":0,"label":"Sat","frontColor":"#177AD5"}]

Solution

  • This will do the trick

    const weekdays = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
    let result = [{ "value": 1, "label": "Tue", "frontColor": "#177AD5" }, { "value": 1, "label": "Thu", "frontColor": "#177AD5" }];
    result = weekdays.map((day, i) => {
      const res = result.findIndex(({ label }) => label === day);   // is label === day
      if (res !== -1) return result.splice(res, 1)[0];              // return the object
      return { "value": 0, "label": day, "frontColor": "#177AD5" }; // else return an object with value 0
    })
    console.log(result)