header_logo
Post thumbnail
JAVASCRIPT

Mastering JavaScript Essentials: RegEx, Map, Reduce, and Filter

By Arun Kumar

When working with data in JavaScript, four essential tools often come up: Regular Expressions, map(), filter(), and reduce(). These tools are powerful, versatile, and widely used in real-world applications. In this article, we’ll go over each one with practical examples and code explanations.

Table of contents


  1. Regular Expressions (RegEx)
    • Real-World Example: Email Validation
  2. Array.prototype.map()
    • Real-World Example: Currency Conversion
  3. Array.prototype.filter()
    • Real-World Example: Filter Adults from a List
  4. Array.prototype.reduce()
    • Real-World Example: Calculate Total Price in a Cart
  5. Summary Table
  6. Conclusion

1. Regular Expressions (RegEx)

Regular Expressions

What it is:
A regular expression is a pattern used to match, search, or validate parts of strings. It’s especially useful when you need to verify user input or extract specific data.

Real-World Example: Email Validation

let email = “user@example.com”;

let pattern = /^[\w.-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/;

if (pattern.test(email)) {

    console.log(“Valid email”);

} else {

    console.log(“Invalid email”);

}

Explanation:

  • ^ and $ mark the start and end of the string.
  • [\w.-]+ matches one or more word characters, dots, or hyphens.
  • @ ensures the email contains the @ symbol.
  • \. checks for a literal dot before the domain.
  • [a-zA-Z]{2,} ensures the domain ends with at least two letters.

Start your coding journey with JavaScript by utilizing Guvi’s FREE E-book on Start Your Development Journey with JavaScript: A beginner’s guide. This e-book provides a detailed overview of JavaScript concepts you need to know.

2. Array.prototype.map()

What it is:
map() is used to transform each element in an array and return a new array of the same length.

Real-World Example: Currency Conversion

let pricesUSD = [10, 20, 30];

let pricesEUR = pricesUSD.map(price => price * 0.9);

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

Explanation: Each price is multiplied by 0.9 (assuming the exchange rate), and the result is stored in a new array. The original array remains unchanged.

3. Array.prototype.filter()

What it is:
filter() returns a new array containing only the elements that satisfy a given condition.

Real-World Example: Filter Adults from a List

let ages = [15, 22, 17, 30, 18];

let adults = ages.filter(age => age >= 18);

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

Explanation: Only ages that are 18 or older are included in the new array. This is useful for creating subsets of data based on criteria.

4. Array.prototype.reduce()

What it is:
reduce() accumulates a single value from an array, which could be a sum, a product, an object, or even a string.

Real-World Example: Calculate Total Price in a Cart

let cart = [100, 250, 75];

let total = cart.reduce((sum, price) => sum + price, 0);

console.log(total); // 425

Explanation: Starting with an initial sum of 0, each item’s price is added to the accumulator. The final value is the total cost of items in the cart.

Summary Table

FeaturePurposeReturnsModifies Original?Common Use Cases
RegExMatch or validate string patternsBoolean/ArrayNoValidating email, passwords
map()Transform each item in an arrayNew arrayNoCurrency conversion, formatting
filter()Extract items based on a conditionNew arrayNoSearch, filtering lists
reduce()Combine the array into a single valueSingle valueNoTotals, summary statistics

Want to learn more about JavaScript? Enroll in Guvi’s course on 100 days of JavaScript with CodeKata. This provides a detailed hands-on coding experience in JavaScript along with important theoretical

MDN

Conclusion

Each of these tools is fundamental for effective JavaScript programming:

  • RegEx helps with pattern matching and validation.
  • map() is perfect for data transformation.
  • filter() is great for extracting specific elements.
  • reduce() allows you to perform calculations and aggregations.

Mastering these will not only make your code cleaner and more expressive but also enable you to handle data processing tasks with confidence and precision.

If you’re interested in seeing how all of these can be used together in a mini-project, feel free to ask!

Success Stories

Did you enjoy this article?

Comments

VSD Technologies
20 days ago
Star Selected Star Selected Star Selected Star Selected Star Selected

Thank you for sharing such valuable insights in this blog post! I found the content very informative and well-presented. The way you explained made it so much easier to understand. I’m looking forward to exploring more of your posts. Keep up the great work!

Schedule 1:1 free counselling

Similar Articles

Loading...
Share logo Copy link
Power Packed Webinars
Free Webinar Icon
Power Packed Webinars
Subscribe now for FREE! 🔔
close
Webinar ad
Table of contents Table of contents
Table of contents Articles
Close button

  1. Regular Expressions (RegEx)
    • Real-World Example: Email Validation
  2. Array.prototype.map()
    • Real-World Example: Currency Conversion
  3. Array.prototype.filter()
    • Real-World Example: Filter Adults from a List
  4. Array.prototype.reduce()
    • Real-World Example: Calculate Total Price in a Cart
  5. Summary Table
  6. Conclusion