Map, Reduce and Filter are Array methods each one will iterate over an array 
and perform a transformation or computation.They are all 'higher order' 
functions because they take user-defined functions as parameters.
Map:
The map() method is used for creating a new array from an existing one by 
applying a callback function to each one of the elements of the first array.
Detailed Syntax for map function in javascript is
array.map(callback(currentValue, index, array), thisArg)
or
array.map((currentValue, index, array)={
    //operate on input & return
}, thisArg)
Here's what each part of the syntax represents:
    array: The array on which the map() method is called.
    callback: A function that will be called once for each element in the 
    array.It can take up to three arguments:
    currentValue: The current element being processed in the array.
    index (optional): The index of the current element being processed.
    array (optional): The array map() was called upon.
    thisArg (optional): An optional parameter that defines the value to be 
    used as this inside the callback function.
Code:
    const person = {
        firstName: "John",
        lastName: "Doe",
        fullName() {
            return this.firstName + " " + this.lastName;
        },
    };
    const people = [
        { firstName: "Alice", lastName: "Smith" },
        { firstName: "Bob", lastName: "Johnson" },
    ];
    const fullNames = people.map(function (item) {
        return (
            this.fullName() + " works with " + item.firstName + " " 
            + item.lastName
        );
    }, person); // Here, 'person' is passed as the 'thisArg'
    console.log(fullNames);
Output:
    [
        'John Doe works with Alice Smith',
        'John Doe works with Bob Johnson'
    ]
Explanation:
   Here person is passed as the 'thisArgs',so when this.fullName() is called 
   it do all calculation based on person object.
In common uses of map() the  'thisArgs' is rarely passed also index,array 
argument are also rare.
Below are common use cases on map().
First Creating Function and then passing it to map() function as callback:
    Code:
        var arr=[16,25,36,49,64]
        function sqrRoot(item){
            return Math.sqrt(item)
        }
        var result = arr.map(sqrRoot)
        console.log(result)
    Output:
        [ 4, 5, 6, 7, 8 ]
Passing callback function to map() function without creating it seperately:
    Code:
        var arr = [16, 25, 36, 49, 64];
        var result = arr.map(function sqrRoot(item) {
            return Math.sqrt(item);
        });
        console.log(result);
    Output:
        [ 4, 5, 6, 7, 8 ]
Passing a ananomous function as callback to map() function:
    Code:
        var arr = [16, 25, 36, 49, 64];
        var result = arr.map(function(item) {
            return Math.sqrt(item);
        });
        console.log(result);
    Output:
        [ 4, 5, 6, 7, 8 ]
Passing a lambda function as callback to map() function
     Code:
        var arr = [16, 25, 36, 49, 64];
        var result = arr.map((item) => Math.sqrt(item));
        console.log(result);
    Output:
        [ 4, 5, 6, 7, 8 ]
    same lambda function can be written with a block of code enclosed in 
    curly braces, and return statement.
     Code:
        var arr = [16, 25, 36, 49, 64];
        var result = arr.map((item) => {
            return Math.sqrt(item)
        });
        console.log(result);
    Output:
        [ 4, 5, 6, 7, 8 ]
Note:
    The result of map() is always a new array, not an object.
    To transform an array into an object, you would typically 
    use other methods like reduce() 
Reduce:
The reduce() method reduces an array of values down to just one value. 
To get the output value, it runs a reducer function on each element of 
the array.
Here's the syntax for the reduce() method:
array.reduce(callback(accumulator, currentValue, index, array), initialValue)
or
array.reduce((accumulator, currentValue, index, array)=.{
    //do some acttion & return 
}, initialValue)
Here's what each part of the syntax represents:
    array: The array on which the reduce() method is called.
    callback: A function that will be called once for each element in the 
    array,taking up to four arguments:
    accumulator: The accumulator accumulates the callback's return values. 
    It is the accumulated value previously returned in the last invocation 
    of the callback,or initialValue if provided.
    currentValue: The current element being processed in the array.
    index (optional): The index of the current element being processed.
    array (optional): The array reduce() was called upon.
    initialValue (optional): A value to use as the initial value of the 
     accumulator. If not provided, the first element in the array will be 
     used as the initial accumulator value and skipped as the currentValue.
Below is an example of reduce() function.
   Code:
    const numbers = [1, 2, 3, 4, 5];
    const sum = numbers.reduce((accumulator, currentValue) => {
    return accumulator + currentValue;
    }, 10);
    console.log(sum);
   Output:
       25
   Explanation:
       Here accumulator has initial value of 10,in each interation 
       currentvalue is getting added to accumulator value.
Here are some variants of same code
   Variant 1:
    Code:
        const numbers = [1, 2, 3, 4, 5];
        const sum = numbers.reduce((accumulator, currentValue) => {
        accumulator = accumulator + currentValue;
        return accumulator
        }, 10);
        console.log(sum);
    Output:
       25
  Variant2:
    Code:
        const numbers = [1, 2, 3, 4, 5];
        const sum = numbers.reduce((accumulator, currentValue) => {
        return accumulator = accumulator + currentValue;
        }, 10);
        console.log(sum); 
    Output:
       25
reduce() can be used to transform an array of strings into a single object 
that shows how many times each string appears in the array.
Code:
    let pets = ["dog", "chicken", "cat", "dog", "chicken", "chicken", "rabbit"];
    let petCount = pets.reduce((accumulator, currentValue) => {
    if (accumulator[currentValue] == undefined) {
        accumulator[currentValue] = 1;    
    } else {
        accumulator[currentValue] = accumulator[currentValue] + 1;
    }
    return accumulator
    }, {});
    console.log(petCount);
Output:
   { dog: 2, chicken: 3, cat: 1, rabbit: 1 }
Here is another example of reduce
Code:
    let pets = [
        ["dog", "med"],
        ["chicken", "feathury"],
        ["cat", "bil"],
        ["dog", "bob"],
        ["chicken", "minny"],
        ["chicken", "shelly"],
        ["rabbit", "binny"],
    ];
    let petCount = pets.reduce((accumulator, currentValue) => {
        var elem = {"type":currentValue[0],"name":currentValue[1]}
        accumulator.push(elem)
        return accumulator;
    }, []);
    console.log(petCount);
Output:
    [
        { type: 'dog', name: 'med' },
        { type: 'chicken', name: 'feathury' },
        { type: 'cat', name: 'bil' },
        { type: 'dog', name: 'bob' },
        { type: 'chicken', name: 'minny' },
        { type: 'chicken', name: 'shelly' },
        { type: 'rabbit', name: 'binny' }
    ]
You can use the reduce() method in JavaScript to convert an array into an 
object by accumulating key-value pairs from the array elements. 
Here's an example of how to do that:
Code:
    const array = [
        { key: 'name', value: 'John' },
        { key: 'age', value: 30 },
        { key: 'city', value: 'New York' }
    ];
    const obj = array.reduce((acc, item) => {
        acc[item.key] = item.value;
        return acc;
    }, {});
    console.log(obj);
Output:
   { name: 'John', age: 30, city: 'New York' }
Filter:
The filter() method takes each element in an array and it applies 
a conditional statement against it. If this conditional returns 
true, the element gets pushed to the output array. If the 
condition returns false, the element does not get pushed to 
the output array.
Syntax of filter method:
array.filter(callback(element, index, array), thisArg)
or
array.filter((element, index, array)=>{
    //do something with input & return
}, thisArg)
Here's what each part of the syntax represents:
    array: The array on which the filter() method is called.
    callback: A function that will be called once for each 
        element in the array, taking up to three arguments:
    element: The current element being processed in the array.
    index (optional): The index of the current element being processed.
    array (optional): The array filter() was called upon.
    thisArg (optional): An optional parameter that defines the value to 
    be used as this inside the callback function.
Example of filter with thisArg:
Code:
    const numbers = [1, 2, 3, 4, 5];
    const thresholdFilter = numbers.filter(function(element) {
        return element > this.threshold;
    }, { threshold: 3 });
    console.log(thresholdFilter); // Output: [4, 5]
Output:
   [4,5]
Explanation:
   Here thisArg is { threshold: 3 }.we can get value from thisArg in callback 
   function inside this.If callback function is not normal function but arrow 
   function them we will not get anything in this hence it is undefined.
Doing same code using lambda function:
Code:
    const numbers = [1, 2, 3, 4, 5];
    // Create an object with the threshold property
    const context = { threshold: 3 }; 
    const thresholdFilter = numbers.filter((element) => {
    return element > context.threshold;
    });
    console.log(thresholdFilter); // Output: [4, 5]
Output:
   [4,5]
Explanation:
   Here we are not passing thisArg instead we are using a context object 
   defined in outer scope
Common example of reduce:
   Code:
       const numbers = [1, 2, 3, 4, 5];
        var even = numbers.filter((m) => {
            return m % 2 == 0;
        });
        console.log(even);
   Output:
        [2,4]
    Explanation:
        numbers array get filtered we get even as for any number(m), m%2==0 
        only when it is even.
 
No comments:
Post a Comment