Filtering arrays
👩🎓: Let's break down the text further:
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.
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.
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.
Filtering Arrays:
- The text presents a custom
filterfunction 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
filterarray method, which achieves the same result more concisely.
- The text presents a custom
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:
Function Definition:
- The code defines a function named
filterwhich takes two parameters: an array (array) and a test function (test).
- The code defines a function named
Initializing an Empty Array:
- Inside the function, an empty array named
passedis initialized. This array will store the elements of the input array that pass the test.
- Inside the function, an empty array named
Iterating Over the Input Array:
- The code then iterates over each element (
element) of the input array using afor...ofloop. - check for detailed explanation this link
- The code then iterates over each element (
Testing Each Element:
- For each element, it checks if the result of applying the
testfunction to that element is true. - If the result is true, meaning the element passes the test, it is added to the
passedarray using thepushmethod.
- For each element, it checks if the result of applying the
Returning the Result:
- After iterating over all elements, the function returns the
passedarray, which contains only the elements that passed the test.
- After iterating over all elements, the function returns the
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 thelivingproperty of each script object is true.
- The first argument is an array named
- The result is logged to the console using
console.log.
- The function is then called with two arguments:
Explanation of
filterFunction:- The
filterfunction 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.
- The
Standard Array Method:
- It's mentioned that
filteris a standard array method, similar toforEach. - Instead of defining the
filterfunction explicitly, the code suggests using the built-infiltermethod of arrays directly.
- It's mentioned that
Usage of
filterMethod:- An example is provided where the
filtermethod is used directly on theSCRIPTSarray to filter out scripts where thedirectionproperty is"ttb"(top-to-bottom).
- An example is provided where the
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: 🦆
Purpose:
- The
filtermethod 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.
- The
Functional Programming Paradigm:
- The
filtermethod is indeed a functional programming concept. Functional programming emphasizes using pure functions and avoiding changing state or mutable data. Thefiltermethod follows this paradigm by not modifying the original array and instead creating a new array with filtered elements.
- The
Syntax:
- The syntax for using the
filtermethod is straightforward:
- The syntax for using the
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 arrayfilterwas called upon.
- The
callbackfunction should returntrueto keep the element, orfalseotherwise. - //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), thefiltermethod automatically passes three arguments to yourcallbackfunction: the current element, its index (if provided), and the original array (if provided). You can use these arguments inside yourcallbackfunction to make decisions about whether to include each element in the new array.
Behavior:
- The
filtermethod iterates over each element of the array and applies the callback function to each element. - If the callback function returns
truefor an element, that element is included in the new array. - If the callback function returns
falsefor an element, that element is excluded from the new array.
- The
Immutability:
- One of the key features of the
filtermethod 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.
- One of the key features of the
Functional Way vs. Imperative Way:
- The
filtermethod 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
filtermethod leads to cleaner, more concise, and often more readable code, as it abstracts away the details of iteration and filtering logic.
- The
Example:
- Here's an example demonstrating the usage of the
filtermethod:
- Here's an example demonstrating the usage of the
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:
SCRIPTSis an array of script objects..filter()is called onSCRIPTS, 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 objectsas an argument and checks ifs.directionequals"ttb".- If
s.directionis"ttb", the function returnstrue, and the script objectsis included in the new arrayttbScripts. ttbScriptswill then contain all script objects fromSCRIPTSwhosedirectionproperty is"ttb".

Comments
Post a Comment