Map, Filter, and Reduce in JavaScript

Photo by NASA on Unsplash

Map, Filter, and Reduce in JavaScript

In this blog, we are going to learn about map filters and reduce functions in javascript.
map, filter and reduce all three are higher-order functions means all three accept another function as an argument.

  1. map: map function is used for the transformation of an array what do we mean by that suppose we have given one array with integer values and we need to double the value of all the elements we have in the array in this case we can use the map function because we wanted to transform the value of each element we have in the array. Let's see the example.

     let arr = [2,4,1,5,6];
    
     const doubleMe = (val) => {
      // How do we double the value
      // This val will be each value that we have in array
     return 2 * val;
     }
     let doubles = arr.map(doubleMe);
     // lets triple me 
     const tripleMe = (val) => {
     return 3 * val;
     }
     let triples = arr.map(tripleMe);
    
     console.log("Doubles => ",doubles);
     console.log("Triples => ",triples);
    

    see in the above example we are passing doubleMe and tripleMe functions now these functions will be called for each array item and will double and triple the value of the element and the map function will return the new array will those double and triple values.

     // Output for above code
       Doubles =>  [4,8,2,10,12]
       Triples =>  [6,12,3,15,18]
    

    Now there are different ways you can write a map function like by creating an arrow function or directly passing a function inside the map but the end goal and output will be the same just for learning let's see different ways to write that function.

     let arr = [2,4,1,5,6];
    
     let doubles = arr.map((val) => {
          return val * 2;
       })
     // Arrow function
     let triples = arr.map(x => x * 3); // Simplest
    
     // or you can directly pass entire function into map
     const binary = arr.map(function convert(val){
       return val.toString(2); // covert to binary
     })
    

    And this way we can use the map function for array transformation.

  2. filter: filter is the simplest function to explain because it does what its name says yes filter is used to filter the array basically when you have an array and you wanted to filter based on some condition at that time we can use a filter and the filter function will also return an array with filtered value. Let's see an example where we will filter even numbers and odd numbers from an array.

     // Few examples of fliter function
    
     let arr = [2,5,4,7,9,11];
     let evenNums =  arr.filter(x => x%2 === 0); 
     console.log(evenNums); // OUTPUT : [2, 4]
    
     let oddNums =  arr.filter(x => x%2 !== 0); 
     console.log(oddNums); // OUTPUT : [5, 7, 9, 11]
    
     // One example where we need all values that are greater then 5
    
     let greaterThen5 = arr.filter(x => x > 5);
     console.log(greaterThen5); // OUTPUT [7, 9, 11]
    

    Now in the above example, we are using arrow functions but the same as the map we can pass the entire function inside the filter or create the function outside and then pass it into the filter function arrow functions is more simple and readable that's why we are using arrow functions directly.

  3. reduce: The reduce() function in JavaScript can be used to iteratively process elements of an array and reduce them to a single value. Here's an example that demonstrates how it works:

     const numbers = [1, 2, 3, 4, 5];
    
     const sum = numbers.reduce(function(accumulator, currentValue) {
       return accumulator + currentValue;
     });
    
     console.log(sum); // Output: 15
    

    In this example, the reduce() function takes a callback function as its argument, which is executed on each element of the numbers array. The callback function takes two arguments: accumulator, which is the accumulated result of the previous operations, and currentValue, which is the current element of the array being processed. The callback function returns the updated value of the accumulator after each iteration.

    In the end, reduce() returns the final value of the accumulator, which in this case is the sum of all the elements in the numbers array. Let's see one more example where we have to calculate the total cost of items in a shopping cart.

     const cartItems = [
       { name: "Product A", price: 10.99, quantity: 2 },
       { name: "Product B", price: 5.99, quantity: 3 },
       { name: "Product C", price: 2.99, quantity: 1 }
     ];
    
     const totalCost = cartItems.reduce(function(accumulator, currentValue) {
       return accumulator + (currentValue.price * currentValue.quantity);
     }, 0);
    
     console.log(totalCost); // Output: 39.94
    

    In this example, the reduce() function is used to calculate the total cost of all the items in the cartItems array. The callback function takes two arguments: accumulator, which is the accumulated result of the previous operations, and currentValue, which is the current object being processed. The callback function returns the updated value of the accumulator after each iteration, which is the sum of the current item's price multiplied by its quantity.

    The initial value of the accumulator is 0. In the end, reduce() returns the final value of the accumulator, which in this case is the total cost of all the items in the shopping cart.

That's all about Map, Filter, and Reduce in JavaScript And thanks to Akshay Saini for creating an incredible Namaste Javascript playlist this blog is just whatever learning I had from there.