Skip to main content

5. 7 Summarizing with reduce

 Summarizing with reduce   Understanding Reduce Purpose of Reduce : reduce is a higher-order function used to compute a single value from an array. It's instrumental in operations like summing up numbers or finding an item in an array that meets a specific criterion (e.g., the script with the most characters). Operation : It works by repeatedly taking an element from the array and combining it with a current value until all elements have been processed. This process is akin to folding or reducing the array into a single value. 🎨: Think of reduce like making juice from oranges. You start with a bunch of oranges (the array), and then you squeeze them one by one into a jug (the single value). Your hands (the combining function) do the squeezing, and you might already have some juice in the jug to start with (the start value). 👩‍🎓: The Mechanics of reduce - The reduce function takes three arguments: the array to reduce, a combining function, and a starting value. The combin...

5. 5 Filtering arrays

 Filtering arrays

 


⚙️:Let's break it down step by step:

  1. Introduction to Data Processing with Higher-order Functions:

    • The text begins by highlighting the usefulness of higher-order functions in data processing.
  2. Data Set about Scripts:

    • It mentions the usage of a data set related to scripts, such as Latin, Cyrillic, or Arabic writing systems.
    • The Unicode system assigns a unique number to each character in written language, and most characters are associated with a specific script.
    • Unicode standardizes 140 different scripts, with 81 still in use and 59 historic.
    • The author expresses appreciation for the diversity of writing systems.
  3. Example Data Set and SCRIPTS Binding:

    • An example data set called SCRIPTS is introduced, containing information about the 140 scripts defined in Unicode.
    • Each script is described by an object containing various properties like name, Unicode ranges, direction, origin time, living status, and a link for more information.
  4. Filtering Arrays:

    • The text presents a function named filter that filters elements in an array based on a given test function.
    • The function filter(array, test) iterates through each element in the array, collecting only the elements that pass the test.
    • It emphasizes that the filter function builds a new array without modifying the original array, making it a pure function.
    • The filter function is compared to the standard array method filter, which achieves the same result but is more concise.

Now, let's dive deeper into each section to ensure a thorough understanding.

👩‍🎓: Let's break down the text further:

  1. Introduction to Data Processing with Higher-order Functions:

    • Higher-order functions are functions that can take other functions as arguments or return functions as results. They are particularly useful in scenarios like data processing, where operations need to be applied to collections of data.
  2. Data Set about Scripts:

    • The text discusses a data set related to scripts, which are writing systems like Latin, Cyrillic, or Arabic.
    • Unicode, as introduced in Chapter 1, assigns a unique number to each character in written language. Most characters are associated with specific scripts, and Unicode standardizes 140 different scripts.
    • The author expresses appreciation for the diversity of writing systems, acknowledging the existence of numerous scripts beyond those they personally know.
  3. Example Data Set and SCRIPTS Binding:

    • An example data set named SCRIPTS is mentioned, containing information about the 140 scripts defined in Unicode.
    • Each script is described by an object with properties like name, Unicode ranges, direction, origin time, living status, and a link for more information.
  4. Filtering Arrays:

    • The text presents a custom filter function that iterates through an array and collects elements that pass a given test function. It emphasizes that this function creates a new array without modifying the original one, making it a pure function.
    • It also mentions the standard filter array method, which achieves the same result more concisely.

function filter(array, test) {
  let passed = [];
  for (let element of array) {
    if (test(element)) {
      passed.push(element);
    }
  }
  return passed;
}

console.log(filter(SCRIPTS, script => script.living));
// → [{name: "Adlam", …}, …]
  

🦆 Let's break down the code step by step:

  1. Function Definition:

    • The code defines a function named filter which takes two parameters: an array (array) and a test function (test).
  2. Initializing an Empty Array:

    • Inside the function, an empty array named passed is initialized. This array will store the elements of the input array that pass the test.
  3. Iterating Over the Input Array:

    • The code then iterates over each element (element) of the input array using a for...of loop.
    • check for detailed explanation this link
  4. Testing Each Element:

    • For each element, it checks if the result of applying the test function to that element is true.
    • If the result is true, meaning the element passes the test, it is added to the passed array using the push method.
  5. Returning the Result:

    • After iterating over all elements, the function returns the passed array, which contains only the elements that passed the test.
  6. Usage:

    • The function is then called with two arguments:
      • The first argument is an array named SCRIPTS.
      • The second argument is an arrow function (script => script.living) which checks if the living property of each script object is true.
    • The result is logged to the console using console.log.
  7. Explanation of filter Function:

    • The filter function is explained to build a new array with only the elements that pass the test, without modifying the original array. This makes the function pure.
  8. Standard Array Method:

    • It's mentioned that filter is a standard array method, similar to forEach.
    • Instead of defining the filter function explicitly, the code suggests using the built-in filter method of arrays directly.
  9. Usage of filter Method:

    • An example is provided where the filter method is used directly on the SCRIPTS array to filter out scripts where the direction property is "ttb" (top-to-bottom).

So, in summary, the code defines a function called filter which filters elements of an array based on a given test function, and then demonstrates its usage both as a custom function and as a built-in array method. The key concept emphasized is that the filter function creates a new array without modifying the original array. Let me know if you need further clarification on any part of the code!

🧑I need explanation on the filter method. I need detailed break down. 

Certainly! Let's break down the filter method in more detail: 🦆

  1. Purpose:

    • The filter method is used to create a new array with all elements that pass a test implemented by the provided function. In other words, it selectively includes elements from an existing array based on a condition.
  2. Functional Programming Paradigm:

    • The filter method is indeed a functional programming concept. Functional programming emphasizes using pure functions and avoiding changing state or mutable data. The filter method follows this paradigm by not modifying the original array and instead creating a new array with filtered elements.
  3. Syntax:

    • The syntax for using the filter method is straightforward:
     


let newArray = array.filter(callback(element[, index, array]));

      • array: The original array to be filtered.
      • callback: A function to test each element of the array. It takes three arguments:
        • element: The current element being processed in the array.
        • index (optional): The index of the current element being processed in the array.
        • array (optional): The array filter was called upon.
      • The callback function should return true to keep the element, or false otherwise.
      • //The square brackets [ ] around index and array indicate that
        they are optional parameters. You can choose to include them
        or leave them out when defining your callback function.
      • So, when you call array.filter(callback), the filter method automatically passes three arguments to your callback function: the current element, its index (if provided), and the original array (if provided). You can use these arguments inside your callback function to make decisions about whether to include each element in the new array.

  1. Behavior:

    • The filter method iterates over each element of the array and applies the callback function to each element.
    • If the callback function returns true for an element, that element is included in the new array.
    • If the callback function returns false for an element, that element is excluded from the new array.
    •  
  2. Immutability:

    • One of the key features of the filter method is immutability. It does not modify the original array but creates a new array with the filtered elements.
    • This immutability is in line with the principles of functional programming, where functions do not have side effects and avoid mutating data.
  3. Functional Way vs. Imperative Way:

    • The filter method represents a more functional way of filtering elements from an array compared to the imperative way, which involves manually iterating over the array, applying a condition, and building a new array.
    • Using the filter method leads to cleaner, more concise, and often more readable code, as it abstracts away the details of iteration and filtering logic.
  4. Example:

    • Here's an example demonstrating the usage of the filter method:

     


const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4]

  

Let's say you have a list of numbers [1, 2, 3, 4, 5] and you want to create a new list containing only the even numbers. Here's how you would use the filter method:

In this example, the condition num % 2 === 0 checks if each number is even.
The filter method then creates a new list (evenNumbers) containing only the even numbers
from the original list (numbers).

Result:

The evenNumbers array contains only the elements from the original array (numbers)
that satisfy the condition (i.e., the even numbers).

 

In summary, 

the filter method is a powerful tool in functional programming for selectively extracting elements from an array based on a condition while maintaining immutability and adhering to the principles of functional programming. Let me know if you need further clarification!

🧑 Dummy question about the syntax

🤖 When you see syntax like s.direction in the context of a filter method, it refers to accessing a property named direction of an object s. In JavaScript, objects are collections of properties, and each property has a name (also called a key) and a value. The . notation allows you to access the value of a specific property of an object.

For example, if you have an object representing a script, like so:


let script = {
  name: "Latin",
  direction: "ltr", // ltr stands for left-to-right
  living: true
};

  

You can access the direction property of this object using script.direction, which would give you the value "ltr".

In the context of a filter method, you might use this to filter an array of such objects. Let's say you have an array of script objects (SCRIPTS), and you want to find only those scripts that are written in a certain direction, like "ttb" (top-to-bottom). You could write:

 


let ttbScripts = SCRIPTS.filter(s => s.direction == "ttb");

  

In this line:

  • SCRIPTS is an array of script objects.
  • .filter() is called on SCRIPTS, creating a new array with only the elements that pass the test.
  • s => s.direction == "ttb" is a function passed to .filter() (the callback function) that takes each script object s as an argument and checks if s.direction equals "ttb".
  • If s.direction is "ttb", the function returns true, and the script object s is included in the new array ttbScripts.
  • ttbScripts will then contain all script objects from SCRIPTS whose direction property is "ttb".

Comments