I have an array of objects in my NodeJS project. Each object contains two values -
[{
travelDate: "2023-04-02",
busNumber: "MKLK890"
}]
By using the busNumber and travelDate I am extracting the city id and operator id for each object. For every travelDate I need an array that contains all unique pairs of city is and operator id. For example, I have the following array of objects with their corresponding cityId and operatorId -
[{
travelDate: "2023-04-02",
busNumber: "MKLK890" // cityId: 17, operatorId: 15
},
{
travelDate: "2023-04-02",
busNumber: "MKLK891" // cityId: 17, operatorId: 15
},
{
travelDate: "2023-04-03",
busNumber: "MKLK890" // cityId: 16, operatorId: 23
},
{
travelDate: "2023-04-03",
busNumber: "MKLK891" // cityId: 16, operatorId: 25
}]
The Map I want for the above data should look like this -
2023-04-02: [{17, 15}],
2023-04-03: [{16,23}, {16, 25}]
The code I have written does not return unique pairs -
let busRecordsCityOprHash = {};
for(let currentRow of data) {
const travelDate = currentRow['Travel Date'];
const busNumber = currentRow['Bus Number'];
const distance = currentRow['Settlement Distance'];
let operatorId, cityId;
let busDetails = await busDayWiseService.getOperatorAndCityIdOfBus({ filter: {busNumber: busNumber.toUpperCase(), fromDate: getZeroTimeDate(travelDate)}})
if(busDetails){
operatorId = busDetails.operatorId;
cityId = busDetails.cityId;
}
const cityOprPair = [cityId, operatorId];
if(!busRecordsCityOprHash[travelDate]) {
busRecordsCityOprHash[travelDate] = new Set();
}
busRecordsCityOprHash[travelDate].add(cityOprPair)
}
Please modify my code to get the required output. Also tell how to iterate the modified data structure?