At my wits end, I think I may be going code blind but can't for the life of me figure out what is causing the issue.
The desired outcome is for there to be only one date per row in the data array and as many flights for each date.
This works for the first item, but not any of the others, ending up with duplicate dates.
Where am I going wrong?
Desired data: example in coming data 5 objects, only two dates.
["2020-02-20", "LGW"]
["2020-02-20", "LTN"]
["2020-02-20", "LHR"]
["2020-02-26", "LTN"]
["2020-02-26", "LHR"]
an array of two objects (one for each date), with the flights an array by date in the respective date object.
data = [ ["2020-02-20", ["LGW","LTN","LHR"]],
["2020-02-26", ["LTN","LHR"]]
]
Code shown below with comments:
function getRows(alternatives) {
var data = [];
for (var i = 0; alternatives.length > i; i++) {
var tmp = new Date(parseInt(alternatives[i].substring(0, 10)) * 1000);
var month = (tmp.getMonth() + 1);
var date = tmp.getFullYear() + "-" + (month < 10 ? "0" + month : month) + "-" + tmp.getDate();
var airport = alternatives[i].slice(11, 14);
var rowData = {
date: date,
flights: []
};
// if data has objects, check to see if the date is in any of the objects, if it isn't then add rowData to data
if (data.length > 0) {
for (var j = 0; data.length > j; j++) {
if (data[j].date === rowData.date) {
//if there are no flights, add the airport, if there are, is the airport already there, if not, add it
if (data[j].flights.length > 0 || !data[j].flights.includes(airport)) {
data[j].flights.push(airport);
}
}
else {
data.push(rowData);
continue;
}
}
}
else {
rowData.flights.push(airport);
data.push(rowData);
}
}
// not working, dupe dates are appearing in the rows
return data;
}