More on Functional Programming

As we've already seen the use of forEach ,map and filter in the previous article Functional Programming with various approach and example.

Now let's try to get the concept reduce, every and sort in detail.

  • reduce() : This method is used when we want to return a single value for any array having multiple elements. It return a modified value without changing the original array so it doesn't execute for an empty array.

Understand it like, you have a piggy bank in which you drop few coins daily and you write it on a piece of paper that on that particular day you've dropped this much amount. At the end of the month you want to calculate the total coins you've collected till now. so you'll sum up those numbers which you've written on that piece of paper and then those multiple numbers will be converted into a single number as sum of your coins. So this is how reduce method is used to reduce large collection and return it in a single value.

Syntax: array.reduce(function(total, element, index, array), initialValue).

Looking at the parameters:

ParameterPurpose
totalIt's compulsory to declare a variable which will store all return value by function.
elementIt's must to pass a variable which holds the each element one by one.
indexIt's optional to pass the index else by default 0 is passed.
arrayIt's also optional to pass the name of array.
initialValueIt depends on user that what initial value he/she wants to pass.

Let's see some problems based on reduce method.

Example 1: A frontend developer has created a shopping website in which multiple items are listed. The view is that once the user clicks on add to cart, that item is being added and the number of items be shown on cart icon. As a programmer you have to write a JavaScript code to handle that items and total price.

let itemPrice=[300,500,435,1234,5900,899];
let nitems=itemPrice.length;
let tPrice=itemPrice.reduce((sum,element)=>{
    return sum+=element;
})
console.log(`The total price of ${nitems} items in you cart is Rs. ${tPrice}`);

Output: The total price of 6 items in you cart is Rs. 9268

So in this way what so item will be selected its total price as well as number of items will be calculated.

Example 2: There is a University BEU which has invited the applicants for guest faculty. The chancellor found that duplicate applications are also coming through the form so he asked you to block the duplicate application number storing in the arrayapplicants. As a developer write a provide him the program to handle the duplicate applications and return him a final arrayverifiedApplicants.

let applicants = [1,6,2,7,4,8,3,9,,5,10,2,3,4,5,];
let verifiedApplicants = applicants.reduce((array, element) => {
    if (!array.includes(element)) {
        array.push(element);
    }
    return array;
}, []);

console.log(verifiedApplicants);

Output: [ 1, 6, 2, 7, 4, 8, 3, 9, 5, 10 ]

Observe the code and output carefully. Here appliacants is an array having different numbers on which reduce method is applied which's being stored in another array named verifiedApplicants . Coming on the syntax of reduce method , as usual a function is passed with two parameters (array, elements) in which array will store certain value returned by the function. In the declaration of function it's checked whether that array is already having that element or not .If it satisfies then that element is pushed in array. Till here we're done with function, now after function [] is declared which is the initialValue that we had seen in syntax. So basically from the initial value (empty array [] used) it's define that variable array(passed as parameter) is an array which will store elements.

  • every() : This method is used when we want to check whether all the elements in collection satisfies the condition or not.

    It returns true or false only. If all the elements satisfies the condition, it returns true else it return false.

    Assume that you are an examination controller of any university. The different subject teachers have submitted the marks scored by a particular student in that subject. Now you need to verify who will be promoted to next class and who not. For this you'll check all the marks in different subject for that student if he/she scores equal to or above the fixed mark you'll say promoted else not promoted. So basically you are verifying for all subjects to pass if a single subject's score is below that you'll not allow him/her

    Syntax is same that of forEach and filter .

    Example 1: Imagine you're managing a delivery service at Flipkart, and you want to ensure that all items whose weight is less than 5kg will only be passed for packing. Take a sample of any 5 items.

    
      let cartItems = [
          { item: "Shoes", weight: 2.3 },
          { item: "shirt", weight: 1.3 },
          { item: "television", weight: 6.9 },
          { item: "bag", weight: 3.2 },
          { item: "luggage", weight: 5.2 },
        ];
    
        let under5kg = cartItems.every((element) => {
          return element.weight < 5;
        });
    
        console.log(under5kg);
    

    Output: False

    Here the condition fails for the item television and luggage so the cart will be blocked.

  • sort() : The method sorts the elements of an array in place and returns the sorted array. The default sorting order is lexicographic (alphabetical) for strings and ascending numerical for numbers.

    Assume it like you're given the name of students to allot roll number alphabetically so using sort method you can easily do that.

    Let's try to get this sort method using some examples.

    Example 1: There is a library in your college having different kinds of books which're kept here and there. One day you thought to make a website where all the books and its shelve number will be shown alphabetically. You're given set of names sort it alphabetically so that librarian can keep it on correct shelve.

  •       let libraryBooks = ["Don Quixote","Alice's Adventures in Wonderland","Treasure Island","A Tale of Two Cities", "Black Beauty"];
            libraryBooks.sort();
            console.log(libraryBooks);
    

    Output: [ 'A Tale of Two Cities', "Alice's Adventures in Wonderland", 'Black Beauty', 'Don Quixote', 'Treasure Island' ]

    Here books are arranged alphabetically.

  • Example 2: You are given a set of numbers to arrange in ascending and descending order using sort method.

      //for ascending order
      let numbers=[8,2,5,4,1,7,0,2,12,10,9];
      numbers.sort((a,b)=>{
        return a-b;
      })
      console.log(numbers);
    
      //for descending order
      let numbers=[8,2,5,4,1,7,0,2,12,10,9];
      numbers.sort((a,b)=>{
        return b-a;
      })
      console.log(numbers);
    

    Output for ascending order:[ 0, 1, 2, 2, 4, 5, 7, 8, 9, 10, 12 ]

    Output for descending order:[ 12, 10, 9, 8, 7, 5, 4, 2, 2, 1, 0 ]

    In this example an array numbers is having different elements on which sort method is applied. In the function two parameters are passed a,b on which the function returns a-b. The function subtracts b from a ;If the result is negative, a comes before b, sorting the array in ascending order.

This is all about different functional programming. In next article we'll see few example where these methods will be used in DOM.

Till then keep learning and practicing these methods with various examples.