I encountered a strange issue that I wasn't expecting.
The snippet of code below represents a simple function.
However, the problem arises when I try to access 'truckArray[0].weight' and receive an error stating TypeError: Cannot read property 'weight' of undefined
To confirm that the value is not undefined, I used console.log(truckArray[0]),
function solution(bridge_length, weight, truck_weights) {
const truckArray = truck_weights.map((v)=>{
return {
weight: v,
movingDistance: 0,
};
});
const inProcess = [];
let timeCount = 0;
let inProcessTotalWeight = 0;
do {
timeCount++;
if ((**truckArray[0].weight** + inProcessTotalWeight) <= weight) {
inProcess.push(truckArray.shift());
}
inProcess.forEach((v)=>{
v.movingDistance += 1;
})
if (inProcess[0].movingDistance > bridge_length) {
inProcess.shift();
}
}while(inProcess.length !== 0 );
return timeCount;
};
I would appreciate any suggestions or ideas. Thank you!