I have this piece of code, but whenever I run findTimeSlots() it immediately messes up my global array apptData but I don't see in anywhere in this function that is supposed to have changed it.
(ConsoleLog)
(index):69
(4) [{…}, {…}, {…}, {…}]
0: {service: "A, B", duration: 50, tech: "C"}
1: {service: "B", duration: 30, tech: "C"}
2: {service: "A, D", duration: 60, tech: "A"}
3: {service: "D", duration: 40, tech: "A"}
length: 4
__proto__: Array(0)
(index):45
(4) [{…}, {…}, {…}, {…}]
0: {service: "A, B", duration: 50, tech: "C"}
1: {service: "B", duration: 30, tech: "C"}
2: {service: "A, D", duration: 60, tech: "A"}
3: {service: "D", duration: 40, tech: "A"}
length: 4
__proto__: Array(0)
///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
var apptData = [];
function addApptData(serviceName, rawDuration, selectedTech){
apptData.push({
'service': serviceName,
'duration': rawDuration,
'tech' : selectedTech
})
}
function reduceApptData(index){
apptData.splice(index, 1);
}
function findTimeSlots(dateStr){
console.log(apptData); //* Index 45 *//
var final = new Array();
var service, duration;
for(var i = 0; i < apptData.length; i++){
var duplicated = false;
for(var j = 0; j < final.length; j++){
if(final[j].tech == apptData[i].tech){
service = ", "+apptData[i].service;
final[j].service += service;
duration = apptData[i].duration;
final[j].duration += duration;
duplicated = true;
break;
}
}
if(!duplicated){
final.push(apptData[i]);
}
}
}
addApptData("A", 20, "C");
addApptData("B", 30, "C");
addApptData("A", 20, "A");
addApptData("D", 40, "A");
console.log(apptData); //* Index 69 *//
// If I remove the line below, I get the expected result, when I try to
// run with this line it will mess up apptData[]
findTimeSlots("");
What I expected to be is
0: {service: "A", duration: 20, tech: "C"}
1: {service: "B", duration: 30, tech: "C"}
2: {service: "A", duration: 20, tech: "A"}
3: {service: "D", duration: 40, tech: "A"}
length: 4
__proto__: Array(0)
So basically I expect it to remain the same.
I wanted to consolidate my var apptData into my var final inside my findTimeSlots()
After debugging, I found out that my apptData keep changing unexpectedly for some reason.
I suspect this to be very trivial but I cannot for the life of me figure out.