I am in search of my final result which should be as follows:
result = [{x: '12/12', y: 90 }, {x: '12/11', y: 0}, {x: '12/10', y: 92}, {x: '12/9', y: 0}, ... ]
Currently, I have two arrays to work with. The first array represents the last 30 days and was generated using momentjs
in this manner:
const lastThirtyDays = [...new Array(31)].map((i, idx) =>
moment()
.startOf('day')
.subtract(idx, 'days')
.format('MM/D'),
);
This produces the following array of dates:
["12/12", "12/11", "12/10", "12/9", "12/8", "12/7", "12/6", "12/5", "12/4", "12/3", "12/2", "12/1", "11/30", "11/29", "11/28", "11/27", "11/26", "11/25", "11/24", "11/23", "11/22", "11/21", "11/20", "11/19", "11/18", "11/17", "11/16", "11/15", "11/14", "11/13", "11/12"]
The second array consists of a collection of numbers associated with certain dates, depicted as follows:
const sampleSet = [
{ date: '2019-12-11', number: 100 },
{ date: '2019-12-10', number: 99 },
{ date: '2019-12-08', number: 101 },
{ date: '2019-12-07', number: 90 },
{ date: '2019-12-05', number: 98 },
{ date: '2019-12-01', number: 96 },
{ date: '2019-11-28', number: 99 },
];
In an attempt to merge these arrays into an x-y dataset, I initially utilized a forEach loop as shown below:
const createDateSet = () => {
let set = [];
lastThirtyDays.forEach((date, i) => {
if (
sampleSet[i] &&
sampleSet[i].date &&
moment(sampleSet[i].date).format('MM/D') === date
) {
set.push({ x: date, y: sampleSet[i].number });
} else {
set.push({ x: date, y: 0 });
}
});
};
However, this approach did not yield the desired outcome. Only one matching entry was found. Subsequently, I attempted to iterate over both arrays simultaneously, resulting in the implementation illustrated below:
const createDataSetBothArrays = () => {
let set = [];
lastThirtyDays.forEach((date, i) => {
let dateItem = sampleSet[i];
if (dateItem) {
sampleSet.forEach((datum, i) => {
if (moment(datum.date).format('MM/D') === date) {
set.push({ x: date, y: datum.number });
}
});
} else {
set.push({ x: date, y: 0 });
}
});
};
Despite this revised strategy, there remained inconsistencies between the paired numbers.
What would constitute the correct course of action for resolving this issue?
Thank you!