Transforming with map
let mapped = [];
A new array named mapped is initialized. This array will store the results of applying the transform function to each element of the input array.
Looping Through the Array:
for (let element of array) {
A for...of loop is used to iterate over each element in the input array. This loop is suitable for iterating over arrays because it provides a simple and readable syntax for accessing each element directly.
Applying the Transformation Function:
mapped.push(transform(element));
Inside the loop, the transform function is called with the current element as its argument. The result of this function call, which is the transformed element, is then added to the mapped array using the push method. This process is repeated for every element in the input array.
Returning the Mapped Array:
return mapped;
After all elements have been transformed and added to the mapped array, the map function returns this new array.
Example Usage
The provided example demonstrates how to use the map function to transform an array of script objects (filtered by their writing direction "rtl" for right-to-left) into an array of their names:
let rtlScripts = SCRIPTS.filter(s => s.direction == "rtl");
console.log(map(rtlScripts, s => s.name));
Filtering Scripts by Direction: The
SCRIPTSarray is filtered to include only scripts with a direction of "rtl". This filtering process is performed using thefilterfunction described in the previous paragraph.Mapping Script Objects to Names: The resulting array from the filter operation,
rtlScripts, is then passed to themapfunction along with a transformation function (s => s.name). This transformation function takes a script object and returns itsnameproperty.Output: The output is a new array containing the names of the scripts that have a direction of "rtl".
Conclusion
The map function is a powerful tool for transforming data in arrays, allowing for clean and readable code. It operates on the principle of applying a given function to each element of an array to produce a new array, without altering the original array. This makes map an essential function in functional programming paradigms, where immutability and pure functions are key concepts.
Comments
Post a Comment