JavaScript in Motion: 10 Essential Array Methods for Travel Agencies 🚀

Let's set the stage for this story. My brother, Vijay, owns a small travel agency 🧳 called Supreme Travel Agency. His job is to help people plan and book their dream vacations. This involves a lot of details: different places to visit, what each customer wants, and how much money they have to spend. It can get pretty complicated! As a computer engineering student, I saw how much Vijay was struggling to keep everything organized. So, I decided to help him out. I created some algorithms using JavaScript array methods to make his work much easier. Let's dive in and see how these array methods solved his issues.

Here's the heart of Vijay's system: A structured dataset containing all the essential travel information 🗃️.

const trips = [
  { "name": "Paris", "continent": "Europe", "countryName": "France", "budget": 248000, "available": true, "kidFriendly": true, "romantic": true, "rating": 5, "activities": ["Eiffel Tower", "Louvre Museum", "Seine River Cruise", "Guided Tours", "Wine Tasting", "Historical Sites"] },
  { "name": "London", "continent": "Europe", "countryName": "United Kingdom", "budget": 439000, "available": true, "kidFriendly": true, "romantic": false, "rating": 4, "activities": ["British Museum", "Buckingham Palace", "London Eye", "Guided Tours", "Historical Sites"] },
  { "name": "New York", "continent": "North America", "countryName": "United States", "budget": 280000, "available": true, "kidFriendly": true, "romantic": false, "rating": 5, "activities": ["Times Square", "Statue of Liberty", "Central Park", "Broadway Shows"] },
  { "name": "Tokyo", "continent": "Asia", "countryName": "Japan", "budget": 200000, "available": true, "kidFriendly": false, "romantic": false, "rating": 5, "activities": ["Shibuya Crossing", "Tokyo Skytree", "Senso-ji Temple", "Cultural Tours", "Historical Sites"] },
  { "name": "Goa", "continent": "Asia", "countryName": "India", "budget": 17000, "available": true, "kidFriendly": true, "romantic": true, "rating": 4, "activities": ["Beaches", "Water Sports", "Spice Plantations", "Nightlife"] },
];

Finding the right vacation spot can be overwhelming. But with JavaScript array methods, it becomes much easier. Let's take a look.

.push()

Vijay wants to add a new destination to his travel offerings: Santorini, Greece. He has gathered the necessary information and wants to add it to his trips dataset.

const newTrip = {
    "name": "Santorini",
    "continent": "Europe",
    "countryName": "Greece",
    "budget": 310000,
    "available": true,
    "kidFriendly": true,
    "romantic": true,
    "rating": 4,
    "activities": ["Oia Village", "Santorini Volcano", "Caldera Views", "Wine Tasting", "Sunset Cruises", "Beach Relaxation"]
};

trips.push(newTrip); // Add newTrip at the end of the `trips` array.

Technical Definition: The push() method of Array instance adds the specified elements to the end of an array and returns the new length of the array.

.sort() and .toSorted()

A budget traveler wants to see all available trips sorted from cheapest to most expensive.

const lowTOHight = trips.toSorted((a, b) => a.budget - b.budget);
console.log("'************************* Chepest to Most Expansive Sorted Trips '*************************")
console.log(lowTOHight);

Technical Definition: The sort() method of Array instances sorts the elements of an array in-place and return the reference to the same array, now sorted. The default sort order is ascending

Here we have used toSorted() method. toSorted() method create new array and store that sorted values and return that new array.

.map()

A couple walks into the Vijay’s travel agency, unsure of where to go for their next adventure. They ask Vijay for a list of all available trip destinations. Using the .map() method, Vijay quickly retrieves and presents a list of destination names with country.

const destinationNames = trips.map(trip => `${trip.name} : ${trip.countryName}`);
console.log("'************************* Names of the Destinations *************************");
console.log(destinationNames);

Technical Definition: map() creates a new array from calling a function for every array element.

.reduce()

One day, Vijay was free and casually browsing through the travel data. A thought crossed his mind: "What if someone wanted to visit all the destinations one by one? How much would the total budget be?" To find out, he decided to use the .reduce() method to sum up the budgets of all available trips.

const totalBudget = trips.reduce((sum, trip) => sum + trip.budget, 0);
console.log("'************************* Total Budget of All Trips *************************");
console.log(totalBudget);

Technical Definition: .reduce() is used to reduce an array to a single value by running a unction on each element of the array.

  • .reduce() method takes two main arguments : A callback function [(sum, trip) => sum + trip.budget] and initial value [In out example its 0].

  • A callback function takes two mandatory parameters: accumulator (in our example its sum) - Stores the result of previous calculations and currentValue (in our example its trip) - The current element of the array.

  • An initial value is starting value for the accumulator. It is optional. If not provided, the first element of the array is used.

.filter()

A customer walks into Vijay's travel agency with a specific request. They say, "We’re looking for a 5-star rated, kid-friendly trip to Asia. Can you help us find the perfect destination?" Without hesitation, Vijay uses the .filter() method to find trips that match their criteria.

const userSepcifiedDestinations = trips.filter(trip => {
  return (trip.rating === 5 && trip.kidFriendly === true && trip.continent === "Asia" && trip.available === true);
});
console.log("'************************* User Specified Destinations *************************");
console.log(userSepcifiedDestinations);

.find()

One day, a group of friends walked into Vijay's travel agency, excited for their next adventure. They said, "Vijay, just find us the first Goa trip available in your database and book it for us!" Without wasting any time, Vijay used the .find() method to locate the first available Goa trip.

const bookGoaTrip = trips.find((trip) => trip.name === 'Goa' && trip.available === true);
console.log("'************************* First Goa Trip *************************");
console.log(bookGoaTrip);

Technical Definition: The find() method of Array instances returns the first element in the provided array that satisfies the provided testing function. If no values satisfy the testing function, undefined is returned.

.some()

One day, a couple walked into Vijay's travel agency with excitement. They said, "We want to explore some places in Gujarat. If there’s any trip available, please book it for us!" Vijay quickly used the .some() method to check if any trips to India were available.

const bookGujaratTrip = trips.some(trip => trip.name === "Gujarat" && trip.available === true);
console.log("'************************* Upcoming Gujarat Trip Available ? *************************");
console.log(bookGujaratTrip ? "Yes" : "No");

Technical Definition: The some() method of ` tests whether at least one element in the array passes the test implemented by the provided function. It returns true if it finds and element otherwise returns false.

.forEach() and .splice()

One day, Vijay thought, "Let’s simplify our dataset and keep only the trips that are actually available for booking." He decided to sanitize the original dataset using forEach and splice to directly remove the unavailable trips.

trips.forEach((trip, index) => {
  if(!trip.available) {
    trips.splice(index, 1);
  }
});
console.log("'************************* After santize real data *************************");
console.log(trips);

Technical Definition: .forEach() method of Array instances executes a provided function once for each array element and splice() method of Array instances changes the contents of an array by removing or replacing existing elements and/or adding new elements in-place .

Conclusion

In this article, we saw how JavaScript array methods helped Vijay simplify his travel agency’s data management. Using methods like .push(), .sort(), .map(), .reduce(), .filter(), .find(), .some(), .forEach(), and .splice(), Vijay could:

  • 🆕 Add new destinations with .push()

  • 💸 Sort trips by budget with .sort() and .toSorted()

  • 🌍 Get a list of destinations with .map()

  • 💰 Calculate total trip costs with .reduce()

  • 🔍 Find trips based on customer needs with .filter(), .find(), and .some()

  • 🧹 Clean up unavailable trips using .forEach() and .splice()

These methods made Vijay’s job easier and more efficient, allowing him to focus on helping customers plan amazing vacations. Thanks to JavaScript, Vijay can now confidently manage his business and tackle any challenge in the travel world! ✈️🌍