I am facing an issue while trying to display a chart and extract specific data from an array.
My goal is to generate a chart based on three columns in a JSON array: Source, Campaign, and Date. The process involves grouping the data, counting it, and then visualizing it on the chart. However, I am encountering difficulties as the outcomes are returning NaN values instead of the desired results. Here is the JSON array that I am working with:
results = [{
"utm-source": "direct",
"utm-campaign": "nothing",
"Date": "2019\/05\/10"
},
{
"utm-source": "direct",
"utm-campaign": "nothing",
"Date": "2019\/08\/08"
},
{
"utm-source": "direct",
"utm-campaign": "nothing",
"Date": "2019\/08\/09"
},
{
"utm-source": "direct",
"utm-campaign": "nothing",
"Date": "2019\/08\/12"
},
{
"utm-source": "google",
"utm-campaign": "spring_sale",
"Date": "2019\/08\/21"
},
{
"utm-source": "facebook",
"utm-campaign": "spring_sale",
"Date": "2019\/08\/21"
},
{
"utm-source": "email",
"utm-campaign": "spring_sale",
"Date": "2019\/08\/21"
}]
Despite my attempts, I have not been able to achieve the desired outcome using this code:
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth();
var date = today.getDate();
// build the last 30 days date array
var last30days = [];
for(var i=0; i<30; i++){
var day = new Date(year, month, date - i);
day = day.toISOString().split("T")[0].replace(/-/g,"/")
last30days.push(day);
}
console.log(last30days);
var finalArray = [];
last30days.forEach(function(day,dayIndex){
results.forEach(function(result,resultIndex) {
var found = result.Date.indexOf(day);
console.log(found);
if(found == 0) {
//console.log(result);
finalArray[result.utm_source] += result.Lead_Source;
} else {
finalArray[result.utm_source] += "0";
}
});
});
The anticipated output should resemble this: https://i.sstatic.net/gbvMT.jpg By comparing this array to another one containing the last 30 days, displaying and tallying the number of leads for direct nothing or facebook spring_sale. For the days without any leads, it should return 0 and represent that on the chart for the corresponding campaign and source displayed only once. Furthermore, the expected format of the array is as follows:
{
"direct": {
"nothing": {
"2019/07/24" : "0",
"2019/07/25" : "0",
...
"2019/08/22" : "0"
}
},
"google": {
"spring_sale": {
"2019/07/24" : "0",
"2019/07/25" : "0",
...
"2019/08/22" : "0"
}
},
"facebook": {
"spring_sale": {
"2019/07/24" : "0",
"2019/07/25" : "0",
...
"2019/08/22" : "0"
}
}
}