1

I am using moment JS to try and input missing dates between startBound and endBound by comparing with the data that is being pulled from an API.

Is there a way to pre-populate the data so it fills the empty dates with a value of y as 0 and adds in the dates between the bounds?

Before

var data = [{
  "x": "2018-05-02",
  "y": 8
}, {
  "x": "2018-05-06",
  "y": 4
}];

var startBound = '2018-05-01'; //Start Date bound
var endBound = '2018-05-07'; //End Date bound

After

var data = [{
  "x": "2018-05-01", //Added
  "y": 0
}, {
  "x": "2018-05-02",
  "y": 8
}, {
  "x": "2018-05-03", //Added
  "y": 0
}, {
  "x": "2018-05-04", //Added
  "y": 0
}, {
  "x": "2018-05-05", //Added
  "y": 0
}, ... etc etc... {
  "x": "2018-05-06",
  "y": 4
}];

var data = [{
  "x": "2018-05-02",
  "y": 8
}, {
  "x": "2018-05-06",
  "y": 4
}];

var startBound = '2018-05-01'; //Start Date bound
var endBound = '2018-05-07'; //End Date bound
var startDate = moment(startBound);
var endDate = moment(endBound);

var days = endDate.diff(startDate, 'd', false);

for (var i = 1; i < days; i++) {
  data.splice(i, 0, {
    "x": startDate.add(1, 'd').toISOString(),
    'y': 0
  })
}

for (var i = 0; i < data.length; i++) {
  console.log(data[i].x);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
scopeak
  • 545
  • 1
  • 5
  • 22
  • Possible duplicate of [Javascript - get array of dates between 2 dates](https://stackoverflow.com/questions/4413590/javascript-get-array-of-dates-between-2-dates) – Hassan Imam May 07 '18 at 12:55
  • @HassanImam Not a dupe, this wants to use the dates to make objects and integrate existing objects as well. – Feathercrown May 07 '18 at 13:00

1 Answers1

2

Probably not the most efficient or elegant answer but it works like a charm!

var data = [{
  "x": "2018-05-02",
  "y": 8
}, {
  "x": "2018-05-06",
  "y": 4
}];

var startBound = '2018-05-01'; //Start Date bound
var endBound = '2018-05-07'; //End Date bound
var startDate = moment(startBound);
var endDate = moment(endBound);
var days = endDate.diff(startDate, 'd', false);

var newData = [];

var valY;

for (var i = 0; i <= days; i++) {
  valY = 0;
  for(var j=0;j<data.length;j++){
    if(data[j].x == startDate.toISOString().split("T")[0]){
      valY = data[j].y;
    }
  }
  newData[i] = {"x":startDate.toISOString().split("T")[0],"y": valY};
  startDate.add(1, 'd');
}

data = newData;

for (var i = 0; i < data.length; i++) {
  console.log(data[i]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.1/moment.min.js"></script>
Feathercrown
  • 2,547
  • 1
  • 16
  • 30
  • Worked like a charm! Thanks very much, makes sense now. – scopeak May 07 '18 at 13:02
  • 1
    Why you are using `.toISOString().split("T")[0]` instead of native moment formatting? Simply use [`format('YYYY-MM-DD')`](http://momentjs.com/docs/#/displaying/format/). – VincenzoC May 07 '18 at 13:30