map, filter & reduce 🙏 Namaste JavaScript Ep. 19 🔥
Understanding Higher Order Functions: Map, Filter, and Reduce
Introduction to Higher Order Functions
- The video introduces higher order functions in JavaScript, specifically focusing on
map,filter, andreduce.
- It emphasizes that while many understand these functions conceptually, their practical applications are often unclear.
Exploring the Map Function
What is the Map Function?
- The
mapfunction is used to transform an array by applying a specific transformation logic to each element.
Examples of Transformation
- Transformations can include:
- Doubling each value in the array.
- Tripling each value.
- Converting numbers to their binary representation.
Implementing the Map Function
- To use
map, initialize an output variable and call it on an array using the dot operator followed by.map().
- A transformation function must be passed into
mapto define how each element should be modified.
Creating Transformation Functions
- An example function for doubling values is defined as:
function double(x)
return x * 2;
- This function is then passed into
map, which applies it across all elements of the original array.
Output Verification
- After executing the code with a console log, the transformed output (e.g., doubled values or tripled values) can be verified.
Advanced Usage of Map Function
Using Anonymous Functions and Arrow Functions
- The video discusses alternative syntaxes for defining functions within
map, including anonymous functions and arrow functions.
Simplifying Syntax
- When using single-line return statements in arrow functions, curly braces and the return keyword can be omitted for brevity.
Conclusion on Map Function Usage
- The map function effectively transforms arrays based on specified logic, creating new arrays from existing data.
Transitioning to Filter and Reduce Functions
Understanding the Filter Function in JavaScript
Introduction to the Filter Function
- The filter function is used to extract specific values from an array based on defined criteria, such as filtering out odd numbers or values greater than a certain threshold.
Examples of Filtering Values
- Various filtering examples include extracting odd numbers, even numbers, and values divisible by three from an array. This demonstrates the versatility of the filter function in handling different conditions.
Implementing the Filter Function
- To implement filtering, one can create a constant output variable and apply the
filtermethod on an array with a specified logic for filtering.
- A custom function (e.g.,
isOdd) can be created to check if a number is odd using modulus operation (X % 2).
Practical Demonstration of Filtering Logic
- When applying the filter logic, only values that meet the condition are returned; for instance, filtering odd numbers results in
[5, 1].
- Similarly, when filtering even numbers using
X % 2 === 0, only[2, 6]is returned.
Advanced Filtering Techniques
- The filter function can also be used to find values greater than four by returning
X > 4, yielding results like[5, 6].
- Different coding styles (like arrow functions or inline functions) can be employed for clarity and efficiency in writing filter logic.
Exploring the Reduce Function
Introduction to Reduce
- The reduce function aggregates all elements of an array into a single value. Its naming may cause confusion as it does not literally "reduce" but rather combines data.
Use Cases for Reduce
- Common use cases include calculating sums or finding maximum values within an array. It serves as a powerful tool for data aggregation.
Transitioning from Non-functional to Functional Programming
- Before diving into reduce implementation, it's beneficial to first understand how similar tasks would be performed using traditional programming methods.
Writing a Sum Function Example
How to Calculate Sum and Maximum Value Using Reduce
Calculating Sum with a For Loop
- The process begins by initializing a variable
sumto zero, which will be used to calculate the total sum of an array.
- A for loop is employed to iterate over each element in the array (
ARR), adding each value to thesumvariable.
- After iterating through all elements, the final sum is returned.
Using Reduce Function for Summation
- The
reducefunction can also be utilized for summing values. It takes a callback function with two parameters:accumulator(ACC) andcurrent.
- The accumulator holds the accumulated result while current represents the current value being processed in the array during iteration.
- In this context, we initialize the accumulator with an initial value of zero, allowing it to accumulate sums as it processes each element.
- When logging the output after applying reduce, it confirms that both methods yield the same result of 17.
Finding Maximum Value in an Array
- To find the maximum value instead of summing, a similar iterative approach is taken where we compare each current value against a maximum variable.
- If any current value exceeds our defined maximum, we update our maximum variable accordingly before returning it at the end of iteration.
Implementing Find Max with Reduce
- Transitioning from traditional logic to using reduce for finding max involves setting up a new reduce function without referencing previous results directly.
How to Use Reduce, Map, and Filter in JavaScript
Understanding the Reduce Function
- The
reducefunction's second argument is the initial value of the accumulator. For finding the maximum, it is set to zero, assuming a non-empty array with positive numbers.
- The accumulator acts as a maximum value tracker. At each iteration, if the current value exceeds this maximum (accumulator), it updates the accumulator.
- Renaming the accumulator to "Max" clarifies its purpose. The logic checks if each current value is greater than Max; if so, Max becomes that current value.
- After implementing this logic and logging output, it successfully returns 6 as the maximum from an example array.
- Acknowledges potential confusion between
map,filter, andreduce, promising further examples for clarity.
Real World Example: Mapping User Data
- Introduces a more complex example involving an array of user objects containing first name, last name, and age properties—simulating data from an API.
- The task is to create a list of full names from these user objects. This requires using the
mapfunction effectively.
- Demonstrates how to use
mapby passing an arrow function that concatenates first and last names for each user object in the array.
- Correctly formats full names by adding spaces between first and last names after initial implementation resulted in no space.
- Successfully outputs a list of full names for all users in the provided data structure using
map.
Challenge: Counting Unique Ages
- Presents a challenge: counting how many users share specific ages within the same user array used previously.
- Explains that we need to identify unique ages and count occurrences—e.g., two users aged 26—and suggests thinking about which method (
map,filter, orreduce) would be appropriate for this task.
- Concludes that
reducewill be used because it allows transforming an array into a single object representing counts of unique values rather than returning multiple items.
Understanding the Reduce Function in JavaScript
Introduction to Reduce
- The speaker introduces the concept of using
reducein JavaScript, emphasizing its function parameters: an accumulator and a current value.
- The initial value for the accumulator is set as an empty object, which will be populated during the reduction process.
Iterating Over Values
- The
reducefunction iterates over each element in the array, with the current parameter representing each object being processed.
- A check is performed to see if a property corresponding to
current.ageexists in the accumulator. If not present, it initializes that property.
Updating Accumulator
- If
current.age(e.g., 26) is not found in the accumulator, it assigns a value of one to that key.
- As more values are processed (like age 75), they are similarly added or updated within the accumulator object.
Final Output and Insights
- When an age already exists in the accumulator, it increments that property's value by one.
- After processing all values, logging shows an output reflecting counts of ages:
26: 2, 50: 1, 75: 1. This demonstrates howreducecan aggregate data effectively.
Exploring Functional Programming Concepts
Power of Functional Programming
- The speaker highlights that
reducecan be used whenever there's a need to derive a single value from an array through iteration.
- Emphasizes functional programming's strength by allowing functions like
map,filter, andreduceto be passed around and utilized flexibly.
Example Using Filter
- Introduces a new example where users need filtering based on age criteria (less than 30).
- Demonstrates using
.filter()method on user objects where only those under age 30 are retained.
Chaining Methods for Desired Output
- Discusses how filtering results yield objects instead of just first names; this leads into chaining methods for further refinement.
- By chaining
.map()after.filter(), it extracts first names from filtered results effectively achieving desired output.
Breakdown of Chaining Process
- Explains step-by-step how filtering reduces user list size before mapping extracts specific properties (first names).
Chaining Methods in JavaScript: Filter, Map, and Reduce
Exploring Method Chaining
- The speaker discusses the beauty of chaining methods like
filterandmapin JavaScript to manipulate arrays effectively.
- A challenge is presented to the audience: find all individuals under 30 years old and extract their first names using the
reducemethod instead of traditional methods.
- The speaker emphasizes that while they provided an example using
filterandmap, it is possible to achieve similar results withreduce, encouraging viewers to explore this approach.
Upcoming Content on Polyfills
- The next video will cover polyfills for
map,filter, andreduce, which are frequently asked about in interviews for full stack or UI roles.