0
\$\begingroup\$

Suppose I have this array that contains objects:

       var purchasedSeats =[ {
            FlightNumber: '1',
            Price: 25,
          },
          {
            FlightNumber: '1',
            Price: 10,
          },
          {
            FlightNumber: '2',
            Price: 25,
          },
          {
            FlightNumber: '2',
            Price: 25,
          }]

purchasedSeats can be in any order any order Also I have another array which is shown below:

 var Passengers=[{SelectedSeats:[]},{SelectedSeats:[]}];

my goal is to get the output as:

Passengers=[
  {SelectedSeats:[{FlightNumber: '1',Price: 25},{FlightNumber: '2',Price: 25,}]},
  {SelectedSeats:[{FlightNumber: '1',Price: 10},{FlightNumber: '2',Price: 25,}]}
]

Each SelectedSeats shouldn't have same flightnumber.

Below is the code which I have implemented and is working.Is there a better way?

          for (let i = 0; i < Passengers.length; i++) {
          for (let seat = 0; seat < purchasedSeats.length; seat++) {
              console.log(seat)
              if (Passengers[i].SelectedSeats.length === 0) {
                  Passengers[i].SelectedSeats.push(purchasedSeats[seat])
                  purchasedSeats.splice(seat, 1);
              } else {
                  const flightExists = Passengers[i].SelectedSeats.some(function (el) {
                      return el.FlightNumber === purchasedSeats[seat].FlightNumber;
                  });
                  console.log(flightExists);
                  if (!flightExists) {
                      Passengers[i].SelectedSeats.push(purchasedSeats[seat]);
                      purchasedSeats.splice(seat, 1);
                  }
              }
          }
      }
\$\endgroup\$
  • 2
    \$\begingroup\$ You really should add more context around your code example. How is Passengers built? How is purchasedSeats built? Without this info it is difficult to give advice on whether a different data structure might help you avoid your nested loops. \$\endgroup\$ – Mike Brant Jun 3 at 12:52

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.