Skip to main content

Command Palette

Search for a command to run...

Array Methods You Must Know

Published
3 min read
Array Methods You Must Know

Think of an array as a toolbox. In our last post, we learned how to look inside the box. Now, we’re learning how to add, remove, and transform the tools inside without breaking a sweat.

Following are the topics that we are going to cover in this blog...

  • push() and pop()

  • shift() and unshift()

  • map()

  • filter()

  • reduce() (basic explanation only)

  • forEach()


Adding & Removing (The Fast Track)

These methods allow you to quickly change the contents of your array.

  • push() / pop(): Work at the end of the array.

  • unshift() / shift(): Work at the beginning of the array.

let stack = ["Book1", "Book2"];

stack.push("Book3"); // ["Book1", "Book2", "Book3"] - Add to end
stack.pop();         // ["Book1", "Book2"] - Remove from end

stack.unshift("Newspaper"); // ["Newspaper", "Book1", "Book2"] - Add to start
stack.shift();              // ["Book1", "Book2"] - Remove from start

Transformation Methods: map(), filter(), & forEach(), reduce()

These are the heavy hitters. They allow you to process every item in an array in one go.

forEach() — The Elegant Loop

Instead of writing a complex for loop, forEach simply performs an action for every item. it will return the output on same array that was earlier.

let users = ["Alice", "Bob", "Charlie"];
users.forEach(name => console.log("User: " + name));

map() — The Transformer

map() creates a new array by performing an operation on every element. It doesn’t change the original; it gives you a modified copy.

let prices = [10, 20, 30];
let discountedPrices = prices.map(p => p * 0.9); 

console.log(discountedPrices); // [9, 18, 27]

filter() — The Security Guard

filter() creates a new array containing only the items that pass a specific "test."

let ages = [12, 25, 17, 30];
let adults = ages.filter(age => age >= 18);

console.log(adults); // [25, 30]

reduce() — The Accumulator

reduce() is used when you want to take an entire array and "squash" it into a single value (like a total sum).

Think of it like a snowball rolling down a hill it keeps gathering more until it reaches the bottom.

let bills = [50, 100, 25];
let total = bills.reduce((accumulator, current) => accumulator + current, 0);

console.log(total); // 175

Conclusion

Using methods like map() and filter() is a milestone in your journey. It marks the transition from writing code that simply "works" to writing code that is functional, clean, and professional.