Find the source and destination flights – Javascript Coding Question

Today’s Javascript challenge:

 

“You have a bunch of airline tickets for a single trip with many connecting flights. Find out which is the source and destination city.

 

The breakdown:

At first sight, this may seem like a complex question. However, let’s look at it this way: The source/origin city will never be a destination, and the destination city will never be an origin city. With this big hint, we can go ahead and tackle this challenge !

Proceed as follows:

 

  1. Make a function called findRoute, with two arrays for the sources and destinations. We’ll of course include our flights array which contains all the airline tickets for this route (syntax: [source, destination]):
    const flights = [
     ['B', 'C'],
     ['E', 'F'],
     ['C', 'D'],
     ['D', 'E'],
     ['A', 'B'],
    ];
    
    const findRoute = flights => {
      let sources = [];
      let destinations = [];
    
  2. Then, we’ll loop through the flights array, and on each iteration, we’ll push the source and destination cities into their respective arrays:
    flights.forEach((flight, index) => {
      sources.push(flight[0]);
      destinations.push(flight[1]);
    });
    
    
  3. To find out the origin city, we choose the item that is not found in the destinations array.To find the destination city, we choose the item that is not found in the sources array.
    let sourceCity = sources.filter(source => !destinations.includes(source))[0];
    let destinationCity = destinations.filter(destination => !sources.includes(destination))[0];

    Array.filter helps us in this task by just returning the items that comply with the filtering function.

 

Full working code:

const flights = [
  ['B', 'C'],
  ['E', 'F'],
  ['C', 'D'],
  ['D', 'E'],
  ['A', 'B'],
];

const findRoute = flights => {
  let sources = [];
  let destinations = [];
  
  flights.forEach((flight, index) => {
    sources.push(flight[0]);
    destinations.push(flight[1]);
  });
  
  let sourceCity = sources.filter(source => !destinations.includes(source))[0];

  let destinationCity = destinations.filter(destination => !sources.includes(destination))[0];
      
  console.log(sourceCity, destinationCity);
};

findRoute(flights);

 

That is all! To be honest, this was a head-scratcher for me at first. In such cases, it helps to stop thinking “in code”, and just deal with the issue as if you physically have the airline tickets in hand. This makes it so much easier!

Do you have any comments to provide or a better way to solve this challenge? Make sure to enter your insights below!

Share your thoughts