0

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?

Roomi
  • 139
  • 8
  • 1
    I would like you to write a **code snippet** with a dummy object having a `cityId` and `operatorId`. Your example object still needs to be shown with the mentioned two data. Once that is done, we will be able to provide a much better solution. – Alok May 16 '23 at 08:06
  • A set follows the same rule as the rest of javascript for objects: 2 objects built separately with the same properties/values will no test as equal because they have a different reference, only objects assigned by reference with `=` will test as equal. This is the same for `indexOf` which finds an object in an array only if it is the same exact reference – Kaddath May 16 '23 at 08:12
  • https://stackoverflow.com/questions/43772320/map-set-to-maintain-unique-array-of-arrays-javascript maybe this will help – cmgchess May 16 '23 at 08:18

0 Answers0