JavaScript Array Methods Explained Like a Road Trip Adventure!

JavaScript Array Methods Explained Like a Road Trip Adventure!

·

11 min read

Struggling to grasp JavaScript array methods? Let’s simplify them with a story!

Sourish, a 4th-year undergraduate student at XYZ University, had just completed his 7th semester along with his nine friends. Since their 8th semester would be their last, and after graduation, they would be occupied with jobs and higher studies, they wanted to make the most of this break. So, they planned an exciting road trip to Ladakh.

To arrange transportation, Akash, one of their friends, rented two cars. The group decided that Akash and Krish would pick up everyone from their respective houses before meeting at Nehru Place.

With everything set, Akash and Krish hopped into their cars—let’s call them Car1 and Car2—and set off to pick up their friends, marking the beginning of their adventure.

What is an Array?

An array is a data structure that allows you to store multiple values of the same or different data type in a single variable. These values can be accessed by their index, with the first element typically starting at index 0.

This is the way how an Array is declared in JavaScript.

let car1 = ["Krish","Rishi","Arjun","Abhi","Sahil"]
let car2 = ["Akash","Kaushik","Raj","Shub","Sourish"]

Now, the two cars have come to a halt in a place called Murthal after a long journey, and the group is ready for a well-deserved break. They stop at a cozy restaurant and find a table big enough to seat all 10 of them. Just like the two separate groups—Car1 and Car2—coming together to form a complete group, we can think of them as two separate arrays that need to combine to create a single, unified group.

In JavaScript, this is where the concat() method comes into play. Just like how the two carloads of friends merge into one larger group to enjoy lunch together, the concat() method combines two arrays into one new array, allowing all the elements to be part of one cohesive set

  1. Array.concat()

This is one of the array method in JS which can combine two arrays and will return a new array with the two arrays getting combined

Syntax:

concat()
concat(value1)
concat(value1, value2)
concat(value1, value2, /* …, */ valueN)
let car1 = ["Krish","Rishi","Arjun","Abhi","Sahil"]
let car2 = ["Akash","Kaushik","Raj","Shub","Sourish"]

let allFriends = car1.concat(car2);
console.log(allFriends);
//OUTPUT
//["Krish","Rishi","Arjun","Abhi","Sahil","Akash","Kaushik","Raj","Shub","Sourish"]

After a refreshing break at Murthal, the group continued their journey toward Ladakh. The excitement was still fresh, but after driving for a few hours, Akash and Krish, who had been driving since morning, started feeling tired. To keep the journey smooth, they decided to swap seats with their friends.

  • In Car1, Rishi offered to take Krish’s seat, giving Krish a chance to relax.

  • In Car2, Shub and Akash switched places, allowing Akash to rest while Shub took over.

Just like how they changed places within the same car, JavaScript provides a method called splice() that allows us to rearrange elements in an array dynamically by removing and inserting elements at specific positions.

  1. Array.splice()

The splice() method in JavaScript is used to add, remove, or replace elements in an array. It modifies the original array and returns an array containing the removed elements.

Syntax:

splice(start)
splice(start, deleteCount)
splice(start, deleteCount, item1)
splice(start, deleteCount, item1, item2)
splice(start, deleteCount, item1, item2, /* …, */ itemN)
let car1 = ["Krish", "Rishi", "Arjun", "Abhi", "Sahil"];
let car2 = ["Akash", "Kaushik", "Raj", "Shub", "Sourish"];

// Swap Rishi and Krish in Car1
let rishiIndex = car1.indexOf("Rishi");
let krishIndex = car1.indexOf("Krish");

// Remove Rishi and insert him at Krish's position
let removedRishi = car1.splice(rishiIndex, 1)[0];
car1.splice(krishIndex, 0, removedRishi);

// Swap Shub and Akash in Car2
let shubIndex = car2.indexOf("Shub");
let akashIndex = car2.indexOf("Akash");

// Remove Shub and insert him at Akash's position and vice versa
let removedShub = car2.splice(shubIndex, 1)[0];
let removeAkash = car2.splice(akashIndex, 1)[0];

car2.splice(0, 0, removedShub);
car2.splice(shubIndex, 0, removeAkash);

console.log(car1);
// ["Rishi", "Krish", "Arjun", "Abhi", "Sahil"]

console.log(car2);
// ["Shub", "Kaushik", "Raj", "Akash", "Sourish"]

As the road trip continued, the group was mesmerized by the breathtaking landscapes around them. To make the journey even more enjoyable, Arjun decided it was time for some music. Being a huge fan of Michael Jackson, he wanted to listen to one of his iconic songs. To quickly find and play his favorite track, he used a JavaScript array method called filter(), which allows us to search for specific elements within an array based on a condition.

  1. Array.filter()

The filter() method goes through each item in an array and checks if it meets a certain condition. If it does, the item is added to a new array. If not, it is skipped. This method helps in selecting specific elements from an array based on a given rule.

Syntax:

filter(callbackFn)
filter(callbackFn, thisArg)
let music = [
    {artist : "Weeknd", song: "Open Hearts", album: "Hurry Up Tommorow"},
    {artist : "Ed Sheren", song: "Perfect", album: "÷ (2017)"},
    {artist : "Michael Jackson", song: "Billie Jean", album: "Thriller"},
    {artist : "Pink Floyd", song: "Money", album: "Dark Side of the Moon"},
]
let selectedMusic = music.filter((track) => track.song === "Billie Jean")
console.log(selectedMusic); 
// OUTPUT :-
// [
//  { artist: 'Michael Jackson', song: 'Billie Jean', album: 'Thriller' }
// ]

As they continue their journey, Akash notices that one of the cars is low on fuel. They need to find the nearest petrol pump from a list of stops. Here he used find() method to locate the first petrol pump in an array of locations.

  1. Array.find()

The find() method is used to search for an element in an array that meets a specific condition. It returns the first matching element. If no element meets the condition, it returns undefined

Syntax :

find(callbackFn)
find(callbackFn, thisArg)
let petrolPumps = [
  { id: "Petrol-Pump-1", distance: 30 },
  { id: "Petrol-Pump-2", distance: 40 },
  { id: "Petrol-Pump-3", distance: 25 },
  { id: "Petrol-Pump-4", distance: 19 },
];

let nearestPetrolPump = petrolPumps.find((value) => value.distance < 25);
console.log(nearestPetrolPump);
// OUTPUT :-
//{ id: 'Petrol-Pump-4', distance: 19 }

After refueling at a petrol pump, the group resumed their journey. While waiting, some of them bought snacks from a shop next to the petrol pump. Since they planned to split expenses later, Sahil decided to calculate the total amount of money they spent on snacks.

To do this, he used the reduce() method in JavaScript. The reduce() method allows him to sum up the total cost of the snacks by processing each element in the array.

  1. Array.reduce()

The reduce() method in JavaScript executes a provided function (called a reducer function) on each element in an array, resulting in a single output value. It can be used for operations like summing up numbers, finding a product, or even concatenating strings.

Syntax:

reduce(callbackFn)
reduce(callbackFn, initialValue)
let snacks = [
  { snack: "Chips", quantity: 5, price: 50 },
  { snack: "Cold Drink", quantity: 1, price: 100 },
  { snack: "Biscuit", quantity: 8, price: 120 },
  { snack: "Bhujia", quantity: 3, price: 150 },
];
let totalAmount = snacks.reduce((Accumulator,CurrentValue) => Accumulator+CurrentValue.price,0)
console.log(totalAmount); // OUTPUT :- 420

As the journey continued, the group realized they needed to adjust their itinerary. Some stops had to be added, while others had to be removed. Sourish turned to the push() method to add new stops at the end of the itinerary and the pop() method to remove the last stop , making their trip more flexible and adaptable.

  1. Array.pop()

The pop() method of Array instances removes the last element from an array and returns that element. This method changes the length of the array.

Syntax :

pop()
let itinerary = ["Leh", "Pangong Lake", "Nubra Valley","Tso Moriri"]
itinerary.pop()
console.log(itinerary) // OUTPUT :- ["Leh", "Pangong Lake", "Nubra Valley"]
  1. Array.push()

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

Syntax:

push()
push(element1)
push(element1, element2)
push(element1, element2, /* …, */ elementN)
let itinerary = ["Leh", "Pangong Lake", "Nubra Valley"]
itinerary.push("Magnetic Hill")
console.log(itinerary) // OUTPUT :- ["Leh", "Pangong Lake", "Nubra Valley", "Magnetic Hill"]

After a long day of travel, the group finally arrives at their hotel in Leh. The breathtaking view of the mountains and the cozy rooms make it the perfect place to rest.

Once they settle in, they check the total hotel bill, which includes accommodation, dinner, and additional services. After checking into the hotel, the group realizes that not everyone has spent the same amount on accommodation and food. Some booked single rooms, while others shared a room, and a few even ordered extra meals. Instead of splitting the cost equally, Sahil decides to calculate individual payments fairly

Since single rooms are more expensive than shared rooms, Sahil assigns the costs:

  • Single room = ₹2000

  • Shared room = ₹1000 per person

So Sahil used map() method to calculate the total room cost for each person.

  1. Array.map()

The map() method in JavaScript is used to create a new array by applying a function to each element of an existing array. It does not modify the original array; instead, it returns a new array with the transformed values.

Syntax :

map(callbackFn)
map(callbackFn, thisArg)
let expenses = [
  { name: "Sahil", room: "single", food: 500 },
  { name: "Arjun", room: "shared", food: 300 },
  { name: "Krish", room: "shared", food: 400 },
  { name: "Amit", room: "single", food: 600 },
  { name: "Raj", room: "shared", food: 350 },
];
let roomCosts = expenses.map((person) => {
  if (person.room === "single") {
    return { name: person.name, total: 2000 + person.food };
  } else {
    return { name: person.name, total: 1000 + person.food };
  }
});
console.log(roomCosts);
/* OUTPUT :-
[
  { name: 'Sahil', total: 2500 },
  { name: 'Arjun', total: 1300 },
  { name: 'Krish', total: 1400 },
  { name: 'Amit', total: 2600 },
  { name: 'Raj', total: 1350 }
]

After checking in at the hotel and freshening up, the group set out to explore Ladakh’s breathtaking beauty. Their itinerary was packed with iconic destinations, from serene monasteries to high-altitude lakes and thrilling mountain passes.The group’s adventure began with Ladakh’s rich culture, visiting monasteries, Leh Palace, and local markets, ending the day with a delicious Ladakhi dinner.
The next day, they journeyed through Chang La Pass to the stunning Pangong Lake, where they camped under a starry sky.

Day three took them to Nubra Valley, where they explored Diskit Monastery, rode camels in Hunder Sand Dunes, and raced ATVs across the cold desert, staying at a cozy Ladakhi homestay.

On day four, they conquered Khardung La Pass, the highest motorable road, before ending the day with a sunset at Shanti Stupa.

Their final day was spent unwinding at a hillside café, visiting the Hall of Fame Museum, and shopping for souvenirs before heading home, cherishing the unforgettable journey.

To keep track of their five-day adventure, Amit used JavaScript’s forEach() method to log the places they visited.

  1. Array.forEach()

he forEach() method in JavaScript executes a provided function once for each element in an array.

Syntax :

forEach(callbackFn)
forEach(callbackFn, thisArg)
let placesVisited = [
    "Monastery", "Leh Palace", "Local Market", 
    "Pangong Lake", "Chang La Pass", "Nubra Valley",
    "Diskit Monastery", "Hunder Sand Dunes", "Khardung La Pass",
    "Shanti Stupa", "Hall of Fame Museum"
];

console.log("Places we visited during our trip:");
placesVisited.forEach((place, index) => {
    console.log(`${index + 1}. ${place}`);
});
/* OUTPUT :-
Places we visited during our trip:
1. Monastery  
2. Leh Palace  
3. Local Market  
4. Pangong Lake  
5. Chang La Pass  
6. Nubra Valley  
7. Diskit Monastery  
8. Hunder Sand Dunes  
9. Khardung La Pass  
10. Shanti Stupa  
11. Hall of Fame Museum  
*/

After five unforgettable days in Ladakh, the group checked out of the hotel, packed their bags into the car, and got ready to leave. Just as they were about to start the engine, Aman suddenly realized—his wallet was missing!

Panic set in as everyone started searching. They listed all the places he had been before getting into the car.

  1. Array.findIndex()

The findIndex() method of array instances returns the index of the first element that satisfies the provided testing function. If no values match, it returns -1.

Syntax :

findIndex(callbackFn)
findIndex(callbackFn, thisArg)
let placesVisited = [
  { place: "Hotel Room", roomNumber: 205 },
  { place: "Reception", desk: "Front Desk" },
  { place: "Dining Area", table: 12 },
  { place: "Parking Lot", spot: "B2" },
];

let walletLocationIndex = placesVisited.findIndex(spot => spot.place === "Hotel Room");

if (walletLocationIndex !== -1) {
  console.log(`Found the wallet in ${placesVisited[walletLocationIndex].place}, Room Number: ${placesVisited[walletLocationIndex].roomNumber}`);
} else {
  console.log("Wallet is still missing!");
}
/* OUTPUT :-
Found the wallet in Hotel Room, Room Number: 205
*/

With a wave of relief, Aman clutched his wallet, laughing at his own forgetfulness. The group cheered, grateful that the crisis had been averted. With everything finally in place, they hopped into the car and began their journey back home.

As the winding roads of Ladakh stretched behind them, they reminisced about the past five days—the breathtaking landscapes, the thrill of adventure, the warmth of Ladakhi hospitality, and even the little moments of chaos, like this one.

The long drive was filled with laughter, music, and stories. They stopped at a roadside dhaba for one last cup of chai, soaking in the final moments of their trip. As they got closer to home, a quiet sense of nostalgia set in.

Though the journey had ended, the memories would last forever. With a promise to plan another adventure soon, they parted ways, carrying with them stories that would be told for years to come.

Ladakh had given them an unforgettable experience—one that would stay with them forever.

Conclusion

Just like Sourish and his friends planned their Ladakh trip, JavaScript array methods help us navigate data efficiently. Whether combining arrays with concat(), rearranging with splice(), filtering with filter(), or summing costs with reduce(), each method has a purpose—just like every stop on their journey.

Understanding these methods makes coding intuitive, turning arrays into an adventure where each function is a tool for exploration.

THANKS FOR READING