google line chart using start and end date - javascript

I have a start date(01 jan) and end date(31 dec). There are three persons taking photos in between this period.
for example :
var chartData = {
"period":{"startDate":"01 jan","endDate":"31 Dec"},
"person1":[{"date":"01 feb","photos":5},{"date":"15 aug","photos":5}, {"date":"20 dec","photos":5}],
"person2":[{"date":"25 feb","photos":2},{"date":"18 july","photos":8},{"date":"05 nov","photos":2}],
"person3":[{"date":"01 march","photos":4},{"date":"15 aug","photos":1}]
}
I want to create chart by using above data.
Example Chart:
Note: x-axis should be display months in mmm format

You could consider to draw it via Google Line Chart with series.
Since the specified format is not compatible with Google Chart JSON format, the below example demonstrates how to convert it and display:
google.charts.load('current', { packages: ['corechart', 'line'] });
google.charts.setOnLoadCallback(drawChart);
function drawChart() {
var jsonData = {
"period": {
"startDate": "01 jan",
"endDate": "31 Dec"
},
"person1": [
{
"date": "01 feb",
"photos": 5
},
{
"date": "15 aug",
"photos": 5
},
{
"date": "20 dec",
"photos": 5
}
],
"person2": [
{
"date": "25 feb",
"photos": 2
},
{
"date": "18 july",
"photos": 8
},
{
"date": "05 nov",
"photos": 2
}
],
"person3": [
{
"date": "01 march",
"photos": 4
},
{
"date": "15 aug",
"photos": 1
}
]
};
var data = {
"cols": [],
"rows": []
};
//columns
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
addColumn(data, key, (key === "period" ? "date" : "number"));
}
}
var columnPositions = { "person1": 1, "person2": 2, "person3": 3 };
//rows
for (var key in jsonData) {
if (jsonData.hasOwnProperty(key)) {
if (key == "period") {
addRow(data, [parsePeriod(jsonData[key].startDate), null, null, null]); //start
addRow(data, [parsePeriod(jsonData[key].endDate), null, null, null]); //end
} else {
var columnPos = columnPositions[key];
jsonData[key].forEach(function(item) {
var vals = [parsePeriod(item.date), null, null, null];
vals[columnPos] = item.photos;
addRow(data, vals);
});
}
}
}
var dataTable = new google.visualization.DataTable(data);
var options = {
interpolateNulls: true,
hAxis: {
title: 'Period',
format: 'MMM'
},
vAxis: {
title: 'Number of photos'
}
};
var chart = new google.visualization.LineChart(document.getElementById('chart_div'));
chart.draw(dataTable, options);
}
function parsePeriod(value) {
var monthNames = { 'jan': 0, 'feb': 1, 'march': 2, 'apr': 3, 'may': 4, 'jun': 5, 'july': 6, 'aug': 7, 'sep': 8, 'oct': 9, 'nov': 10, 'dec': 11 };
var parts = value.split(" ");
var day = parseInt(parts[0]);
var month = monthNames[parts[1].toLowerCase()];
var d = new Date(2015, month, day);
return d;
}
function addColumn(data, label, type) {
data.cols.push({
"id": "",
"label": label,
"pattern": "",
"type": type
});
}
function addRow(data, values) {
var rowValues = values.map(function (v) {
return { "v": v };
});
data.rows.push({
"c": rowValues
});
}
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<div id="chart_div"></div>

Related

setting a default month & year before filtering a pie chart using FusionCharts

I am working on creating a pie chart with month filter. I have already built it including the filter. when I select a month & year, it filters the data. But I want to set a default value as month(current month) & year(current year). How do I set the default values??
var json = [
{
"Date": "1999-11-03",
"label": "Tatiana Skinner",
"value": 99,
"color": "#f8bd19"
},
{
"Date": "2022-12-18",
"label": "Kato Burke",
"value": 49,
"color": "#f8bd19"
},
{
"Date": "2022-12-18",
"label": "Len Foley",
"value": 41,
"color": "#f8bd19"
}
];
var json2 =[
{
"Date": "2022-12-18",
"label": "Alvin Woodard",
"value": 38,
"color": "#33ccff"
},
{
"Date": "1999-11-03",
"label": "Hop Briggs",
"value": 58,
"color": "#33ccff"
}
];
var json3 = [
{
"Date": "2022-12-18",
"label": "Katell Norton",
"value": 92,
"color": "#ffcccc"
},
{
"Date": "2022-10-11",
"label": "Quinn Parks",
"value": 64,
"color": "#ffcccc"
}
];
// Get a reference to the <input type="month"> element
const monthInput = document.querySelector('input[type="month"]');
// Add an onChange event listener to the input element
monthInput.addEventListener('change', event => {
// Get the value of the input element
const dateString = event.target.value;
// Parse the date string using the Date object
const date = new Date(dateString);
// Extract the year and month values from the Date object
var year = date.getFullYear();
var month = date.getMonth() + 1; // add 1 to the month value, since it is zero-indexed
const data = json.filter(obj => {
// Use a regular expression to check if the Date property
// matches the yyyy-mm-dd format
const dateFormat = /^\d{4}-\d{2}-\d{2}$/;
if (!dateFormat.test(obj.Date)) {
return false;
}
// Split the date string into its component parts
const dateParts = obj.Date.split('-');
const dateYear = parseInt(dateParts[0], 10);
const dateMonth = parseInt(dateParts[1], 10);
// Check if the date year and month match the filter values
return dateYear === year && dateMonth === month;
});
const data2 = json2.filter(obj => {
// Use a regular expression to check if the Date property
// matches the yyyy-mm-dd format
const dateFormat = /^\d{4}-\d{2}-\d{2}$/;
if (!dateFormat.test(obj.Date)) {
return false;
}
// Split the date string into its component parts
const dateParts = obj.Date.split('-');
const dateYear = parseInt(dateParts[0], 10);
const dateMonth = parseInt(dateParts[1], 10);
// Check if the date year and month match the filter values
return dateYear === year && dateMonth === month;
});
const data3 = json3.filter(obj => {
// Use a regular expression to check if the Date property
// matches the yyyy-mm-dd format
const dateFormat = /^\d{4}-\d{2}-\d{2}$/;
if (!dateFormat.test(obj.Date)) {
return false;
}
// Split the date string into its component parts
const dateParts = obj.Date.split('-');
const dateYear = parseInt(dateParts[0], 10);
const dateMonth = parseInt(dateParts[1], 10);
// Check if the date year and month match the filter values
return dateYear === year && dateMonth === month;
});
// console.log(data);
const Incomesum = data.reduce((acc, o) => acc + parseInt(o.value), 0)
const Expensesum = data2.reduce((acc, o) => acc + parseInt(o.value), 0)
const Costsum = data3.reduce((acc, o) => acc + parseInt(o.value), 0)
FusionCharts.ready(function() {
var topProductsChart = new FusionCharts({
type: 'multilevelpie',
renderAt: 'chart-container',
id: "myChart",
width: '500',
height: '500',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Accounts",
"subcaption": "Last Quarter",
"showPlotBorder": "1",
"piefillalpha": "60",
"pieborderthickness": "2",
"piebordercolor": "#FFFFFF",
"hoverfillcolor": "#CCCCCC",
"numberprefix": "tk",
"plottooltext": "$label, $valuetk, $percentValue",
"theme": "fusion"
},
"category": [{
"label": "Account Types",
"color": "#ffffff",
// "value": "150",
"category": [{
"label": "Income",
"color": "#f8bd19",
"value": Incomesum,
"tooltext": "Income, $valuetk, $percentValue",
"category": data
}, {
"label": "Expenses",
"color": "#33ccff",
"value": Expensesum,
"tooltext": "Expenses, $valuetk, $percentValue",
"category": data2
}, {
"label": "Cost of good sold",
"color": "#ffcccc",
"value": Costsum,
"tooltext": "$valuetk",
"category": [{
label: Costsum.toFixed(2),
value: Costsum,
color: '#ffcccc'
}]
}]
}]
}
});
topProductsChart.render();
});
})
<script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
<script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
<form>
<label for="month">Enter the month:</label><br>
<input type="month"><br>
</form>
<div id="chart-container">FusionCharts will render here</div>
In the above snippet, the pie chart will be loaded when you select a month and year. But I want a default value set so the Pie chart will already be loaded when the page is loaded
With a little restructuring you can achieve that. Just move the rendering code to a new function renderChart in the below example. Then you create a load event like this
document.addEventListener("DOMContentLoaded", function() {
const date = new Date();
renderChart(date)
});
which calls the new function and renders with todays date.
var json = [{
"Date": "1999-11-03",
"label": "Tatiana Skinner",
"value": 99,
"color": "#f8bd19"
},
{
"Date": "2022-12-18",
"label": "Kato Burke",
"value": 49,
"color": "#f8bd19"
},
{
"Date": "2022-12-18",
"label": "Len Foley",
"value": 41,
"color": "#f8bd19"
}
];
var json2 = [{
"Date": "2022-12-18",
"label": "Alvin Woodard",
"value": 38,
"color": "#33ccff"
},
{
"Date": "1999-11-03",
"label": "Hop Briggs",
"value": 58,
"color": "#33ccff"
}
];
var json3 = [{
"Date": "2022-12-18",
"label": "Katell Norton",
"value": 92,
"color": "#ffcccc"
},
{
"Date": "2022-10-11",
"label": "Quinn Parks",
"value": 64,
"color": "#ffcccc"
}
];
// Get a reference to the <input type="month"> element
const monthInput = document.querySelector('input[type="month"]');
// Add an onChange event listener to the input element
monthInput.addEventListener('change', event => {
renderChart(event.target.value)
})
document.addEventListener("DOMContentLoaded", function() {
const date = new Date();
renderChart(date)
});
function renderChart(dateString) {
// Get the value of the input element
//const dateString = event.target.value;
// Parse the date string using the Date object
const date = new Date(dateString);
// Extract the year and month values from the Date object
var year = date.getFullYear();
var month = date.getMonth() + 1; // add 1 to the month value, since it is zero-indexed
const data = json.filter(obj => {
// Use a regular expression to check if the Date property
// matches the yyyy-mm-dd format
const dateFormat = /^\d{4}-\d{2}-\d{2}$/;
if (!dateFormat.test(obj.Date)) {
return false;
}
// Split the date string into its component parts
const dateParts = obj.Date.split('-');
const dateYear = parseInt(dateParts[0], 10);
const dateMonth = parseInt(dateParts[1], 10);
// Check if the date year and month match the filter values
return dateYear === year && dateMonth === month;
});
const data2 = json2.filter(obj => {
// Use a regular expression to check if the Date property
// matches the yyyy-mm-dd format
const dateFormat = /^\d{4}-\d{2}-\d{2}$/;
if (!dateFormat.test(obj.Date)) {
return false;
}
// Split the date string into its component parts
const dateParts = obj.Date.split('-');
const dateYear = parseInt(dateParts[0], 10);
const dateMonth = parseInt(dateParts[1], 10);
// Check if the date year and month match the filter values
return dateYear === year && dateMonth === month;
});
const data3 = json3.filter(obj => {
// Use a regular expression to check if the Date property
// matches the yyyy-mm-dd format
const dateFormat = /^\d{4}-\d{2}-\d{2}$/;
if (!dateFormat.test(obj.Date)) {
return false;
}
// Split the date string into its component parts
const dateParts = obj.Date.split('-');
const dateYear = parseInt(dateParts[0], 10);
const dateMonth = parseInt(dateParts[1], 10);
// Check if the date year and month match the filter values
return dateYear === year && dateMonth === month;
});
// console.log(data);
const Incomesum = data.reduce((acc, o) => acc + parseInt(o.value), 0)
const Expensesum = data2.reduce((acc, o) => acc + parseInt(o.value), 0)
const Costsum = data3.reduce((acc, o) => acc + parseInt(o.value), 0)
FusionCharts.ready(function() {
var topProductsChart = new FusionCharts({
type: 'multilevelpie',
renderAt: 'chart-container',
id: "myChart",
width: '500',
height: '500',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Accounts",
"subcaption": "Last Quarter",
"showPlotBorder": "1",
"piefillalpha": "60",
"pieborderthickness": "2",
"piebordercolor": "#FFFFFF",
"hoverfillcolor": "#CCCCCC",
"numberprefix": "tk",
"plottooltext": "$label, $valuetk, $percentValue",
"theme": "fusion"
},
"category": [{
"label": "Account Types",
"color": "#ffffff",
// "value": "150",
"category": [{
"label": "Income",
"color": "#f8bd19",
"value": Incomesum,
"tooltext": "Income, $valuetk, $percentValue",
"category": data
}, {
"label": "Expenses",
"color": "#33ccff",
"value": Expensesum,
"tooltext": "Expenses, $valuetk, $percentValue",
"category": data2
}, {
"label": "Cost of good sold",
"color": "#ffcccc",
"value": Costsum,
"tooltext": "$valuetk",
"category": [{
label: Costsum.toFixed(2),
value: Costsum,
color: '#ffcccc'
}]
}]
}]
}
});
topProductsChart.render();
});
}
<script src="https://cdn.fusioncharts.com/fusioncharts/latest/fusioncharts.js"></script>
<script src="https://cdn.fusioncharts.com/fusioncharts/latest/themes/fusioncharts.theme.fusion.js"></script>
<form>
<label for="month">Enter the month:</label><br>
<input type="month"><br>
</form>
<div id="chart-container">FusionCharts will render here</div>

How to group by api repsons weekly datewise in react native

I am getting below response from api .
Below is sample respone not real
Each object has createdDate , I have to group value is weekwise wise like.
like 2022-10-01 and 2022-10-02 both are 1st week of Oct , and 2022-10-10 3rd Week of Oct
{
"data": {
"fetchOrdersAndRequest": [
{
"id": "PI786971",
"customerId": [
"C200147"
],
"createdDate": "2022-10-01T04:46:00.126Z",
}
{
"id": "PI786972",
"customerId": [
"C200148"
],
"createdDate": "2022-10-02T04:46:00.126Z",
}
{
"id": "PI786972",
"customerId": [
"C200149"
],
"createdDate": "2022-10-10T04:46:00.126Z",
}
{
"id": "PI786969",
"customerId": [
"C200146"
],
"createdDate": "2022-10-24T04:46:00.126Z",
}
{
"id": "PI786968",
"customerId": [
"C200145"
],
"createdDate": "2022-10-29T04:46:00.126Z",
}
]
}
}
I have to convert the response like below , monthly value I have to convert weekly
{
period:'lastMonth',
Week:[
{
"key":"Week1",
"value" : [{
"id": "PI786971",
"customerId": [
"C200147"
],
"createdDate": "2022-10-01T04:46:00.126Z",
}
{
"id": "PI786972",
"customerId": [
"C200148"
],
"createdDate": "2022-10-02T04:46:00.126Z",
}],
"date": [{2022-10-01}{2022-10-02}]
},
{
"key":"Week2",
"value" : [],
"date:[]
},
{
"key":"Week3",
"value" : [{
"id": "PI786972",
"customerId": [
"C200149"
],
"createdDate": "2022-10-10T04:46:00.126Z",
}],
"date":[{2022-10-10}]
},
{
"key":"Week4",
"value" : [{}],
},
{
"key":"week5",
"value" : []
"date":[{2022-10-24}{2022-10-29}]
},
{
"key":"Week6",
"value" : [],
"date:[]
},
]
// Using below code I am able to filter weeks and my weeks startng from sunday to Saturday , but now I have to puch my api response data matching to dates
fetchMonthWeek = ()=>{
var today = new Date();
const month = today.getMonth() + 1
const year = today.getFullYear()
var days = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday'];
let weeks = {}
var totalDays = new Date(year, month, 0).getDate();
let weekCount = 1
for (let i = 1; i <= totalDays; i++) {
const date = (i < 10 ? '0' + i : i)
const fullDate = (year + '-' + (month < 10 ? '0' + month : month) + '-' + date)
const currentDay = days[new Date(fullDate).getDay()]
if (currentDay === days[0]) weekCount++
const w = 'Week' + weekCount
if (weeks[w]) {
weeks[w].push(fullDate)
} else weeks[w] = [fullDate]
}
console.log(weeks)
let newData = []
for (const w in weeks) {
newData.push({
key: w,
range: {
startDate: weeks[w][0],
endDate: weeks[w][weeks[w].length - 1]
},
value: weeks[w]
})
}
return newData
}
Please help .
Thank you

Javascript group object of dates by weeks

I have data like this:
[
{
"time": "2021-07-28T18:16:23.994Z"
},
{
"time": "2021-07-29T18:16:23.994Z"
},
{
"time": "2021-08-01T15:01:40.267Z"
},
{
"time": "2021-08-02T15:01:40.267Z"
},
{
"time": "2020-06-09T15:01:40.267Z"
}
]
and I need a method that will return something like this:
{
"2020": { // year
"07/06-13/06": { // dates of the week
"Tue": "2020-06-09T15:01:40.267Z" // day name at key
}
},
"2021": {
"25/07-31/07": {
"Wed": "2021-07-28T18:16:23.994Z",
"Thu": "2021-07-29T18:16:23.994Z"
},
"01/08-07/08": {
"Sun": "2021-08-01T15:01:40.267Z",
"Mon": "2021-08-02T15:01:40.267Z"
}
}
}
I tried to do this with momentjs and lodash/groupby but without success..
Thanks in advance!
a little bit ugly, but works:
const datesArray = [
{
"time": "2021-07-28T18:16:23.994Z"
},
{
"time": "2021-07-29T18:16:23.994Z"
},
{
"time": "2021-08-01T15:01:40.267Z"
},
{
"time": "2021-08-02T15:01:40.267Z"
},
{
"time": "2020-06-09T15:01:40.267Z"
}
]
function getWeeksRange(date) {
const curr = new Date(date.time);
const first = curr.getDate() - curr.getDay();
const last = first + 6;
const format = { year: 'numeric', month: '2-digit', day: '2-digit' };
var firstday = new Date(curr.setDate(first)).toLocaleDateString("he-IL", format);
var lastday = new Date(curr.setDate(last)).toLocaleDateString("he-IL", format);
;
return `${firstday.slice(0, 5).replaceAll('.', '/')}-${lastday.slice(0, 5).replaceAll('.', '/')}`
}
function groupDatesByWeek(dates) {
const groupedDates = {}
dates.forEach(date => {
const range = getWeeksRange(date);
const dayName = new Date(date.time).toString().split(' ')[0]
if (!groupedDates[date.time.split('-')[0]]) {
groupedDates[date.time.split('-')[0]] = {};
groupedDates[date.time.split('-')[0]][range] = {};
} else if (!groupedDates[date.time.split('-')[0]][range]) {
groupedDates[date.time.split('-')[0]][range] = {};
}
groupedDates[date.time.split('-')[0]][range][dayName] = date.time;
})
return groupedDates;
}
console.log(groupDatesByWeek(datesArray))

momentjs iterate over dates in a two week period and map the date to existing array

I have an array that has a object with two properties, 'location' and 'needs'. The needs property has an array of objects with a date and count {date: "2021-06-15", count: 10} so an array would look like this:
{
"location": "NYC",
"needs": [
{
"date": "2021-04-06",
"count": 56
},
{
"date": "2021-04-13",
"count": 10
}
]
}
What I need to do is to use Momentjs to use today's date, figure out the two week period starting from today, and then map the needs-count to the date in the moment loop. If there is a date missing (like in the example below), it should put a 0 as the count
A final array would look like...
{
"location": "NYC",
"needs": [
{
"date": "2021-04-06",
"count": 56 // this had a count in the initial object
},
{
"date": "2021-04-07",
"count": 0
},
{
"date": "2021-04-08",
"count": 0
},
{
"date": "2021-04-09",
"count": 0
},
{
"date": "2021-04-10",
"count": 0
},
{
"date": "2021-04-11",
"count": 0
},
{
"date": "2021-04-12",
"count": 0
},
{
"date": "2021-04-13",
"count": 10 // this had a count in the initial object
},
...
...
...
]
}
In terms of a function, the closest I have got is
let startDay = moment().format('YYYY-MM-DD');
let endDay = moment().add(14, 'days').format('YYYY-MM-DD');
let startDate = moment(startDay);
let endDate = moment(endDay);
let datesBetween = [];
let startingMoment = startDate;
while(startingMoment <= endDate) {
for (let count = 0; count < 15; count ++) {
// at this point im trying to take 'week' which has the location property and needs property and trying to merge them together... but failed miserably.
if (week.needs[count].date === startingMoment) {
datesBetween.push([startingMoment.clone(), week.needs[count].count]);// clone to add new object
startingMoment.add(1, 'days');
} else {
datesBetween.push([startingMoment.clone(), 0]);// clone to add new object
}
}
}
Can someone see where I went so wrong?
const week = {
"location": "NYC",
"needs": [
{
"date": "2021-04-06",
"count": 56
},
{
"date": "2021-04-13",
"count": 10
}
]
}
let current = moment();
const allDates = [];
const FORMAT = 'YYYY-MM-DD';
for (let count = 0; count < 14; count++) {
const found = week.needs.find(i => i.date === current.format(FORMAT));
if (found) {
allDates.push(found);
} else {
allDates.push({
date: current.format(FORMAT),
count: 0,
});
}
current.add(1, 'day');
}
week.needs = allDates;
console.log(week);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js" integrity="sha512-qTXRIMyZIFb8iQcfjXWCO8+M5Tbc38Qi5WzdPOYZHIlZpzBHG3L3by84BBBOiRGiEb7KKtAOAs5qYdUiZiQNNQ==" crossorigin="anonymous"></script>
You could do something like this :
let dates = {
"location": "NYC",
"needs": [
{
"date": "2021-04-06",
"count": 56
},
{
"date": "2021-04-13",
"count": 10
}
]
};
let day = moment();
for( let i=0; i< 15; i++){
let date = day.add(1, "days").format("YYYY-MM-DD");
console.log(`Looking if ${date} is in array...`)
if(dates.needs.find(obj => obj.date === date)) continue;
console.log(`Adding ${date}`)
dates.needs.push({ date, count : 0 })
}
dates.needs.sort( (a,b) => a.date > b.date ? 1: -1 );
console.log(dates)
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

How to fill dates in an array containing range of dates?

I have an array of dates containing a count value. e.g.
[
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
},
{
"date": "2014-11-13T08:00:00.000Z",
"count": 4
}
{
"date": "2014-11-16T08:00:00.000Z",
"count": 4
}
]
How do I fill in the missing dates with count = 0, to produce the following in javascript:
[
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
},
{
"date": "2014-11-12T08:00:00.000Z",
"count": 0
},
{
"date": "2014-11-13T08:00:00.000Z",
"count": 4
},
...
]
as you appear to be using momentjs
the first thing that came to mind was use the moment().add(number, units) and moment().diff(input, units, asFloat)
something like
var data = [
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
}, {
"date": "2014-11-16T08:00:00.000Z",
"count": 4
}
];
var startDate = moment(data[0].date);
var endDate = moment(data[1].date);
var days = endDate.diff(startDate, 'd', false);
alert(days);
for (var i = 1; i < days; i++) {
data.splice(i,0, {"date" : startDate.add(1, 'd').toISOString(), 'count': 0 })
}
for (var i = 0; i < data.length; i++) {
alert(data[i].date);
}
<script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.8.3/moment.min.js"></script>
Try this:
var arr = [
{
"date": "2014-11-11T08:00:00.000Z",
"count": 8
},
{
"date": "2014-11-16T08:00:00.000Z",
"count": 4
}
];
function fillDates(start, end) {
var output = [start];
var date = new Date(start.date);
var endDate = new Date(end.date);
do {
output.push({
"date": date.toISOString(),
"count": 0
});
date = new Date(date.getTime());
date.setDate(date.getDate() + 1);
} while (date < endDate);
output.push(end);
return output;
}
var start = arr[0];
var end = arr[1];
fillDates(start, end);
const models = [
{
date: '2018-10-17',
value: 3,
},
{
date: '2018-10-20',
value: 4,
},
{
date: '2018-10-21',
value: 5,
},
{
date: '2018-10-27',
value: 6,
},
];
const filledInDates = models.reduce((newArray, currentModel, index, originalArray) => {
const nextModel = originalArray[index + 1];
if (nextModel) {
const currentDate = moment(currentModel.date);
const daysBetween = moment(nextModel.date).diff(currentDate, 'days');
const fillerDates = Array.from({length: daysBetween - 1}, (value, dayIndex) => {
return {
value: currentModel.value,
date: moment(currentDate).add(dayIndex + 1, 'days').format('YYYY-MM-DD'),
};
});
newArray.push(currentModel, ...fillerDates);
} else {
newArray.push(currentModel);
}
return newArray;
}, []);
console.log(filledInDates);
Output:
[
{value:3, date:"2018-10-17"},
{value:3, date:"2018-10-18"},
{value:3, date:"2018-10-19"},
{value:4, date:"2018-10-20"},
{value:5, date:"2018-10-21"},
{value:5, date:"2018-10-22"},
{value:5, date:"2018-10-23"},
{value:5, date:"2018-10-24"},
{value:5, date:"2018-10-25"},
{value:5, date:"2018-10-26"},
{value:6, date:"2018-10-27"}
]

Categories