Core points
Array
and map()
methods of reduce()
objects are powerful functional programming tools that make the code more concise, readable and easy to maintain. map()
is a basic functional programming technique that acts on all elements in an array and generates another array of the same length that contains the converted content. By adding mapping functionality to array objects, ECMAScript 5 turns the basic array type into a complete functor, making functional programming easier to use. reduce()
method (also a new method in ECMAScript 5) is similar to map()
, but instead of generating another functor, it generates a single result, which can be of any type. It applies the functions in order to each element of the array so that the array is reduced to a single output value. map()
and reduce()
methods may affect performance, the improvements in code quality and developer satisfaction today with using them are likely to outweigh any temporary impact on performance. The author recommends using functional techniques for development and measuring the impact in real-world situations before deciding whether map()
and reduce()
are suitable for a certain application. The process discussions related to many amazing new features of ECMAScript 6 are rampant, and it’s easy to forget that ECMAScript 5 provides some great tools for us to support functional programming in JavaScript, which we can do today use. These include native Array
and map()
methods based on JavaScript reduce()
objects.
If you haven't used map()
and reduce()
yet, then start now! Most modern JavaScript platforms support ECMAScript 5 natively. Mapping and regulations can make your code more concise, easier to read and maintain, and guide you towards more elegant functional development.
Performance: Precautions
Of course, when needed, the reading and maintenance of the code must be balanced with performance. Currently, browsers are more efficient using more cumbersome traditional techniques such as for
loops.
My approach is usually to write code that is easy to read and maintain first, and then optimize performance if I notice the problem in the actual situation. Premature optimization is the source of all evil.
It is also worth considering that as browsers optimize map()
and reduce()
, using these methods may make better use of the improvements in the JavaScript engine. Unless I'm facing performance issues, I prefer to write code optimistically and put performance tweaks that make my code less attractive in my backup pocket in case I need them.
Use Map
Mapping is a basic functional programming technique that acts on all elements in an array and generates another array of the same length (including the converted content).
To be more specific, let's come up with a simple use case. For example, suppose you have an array of words that you need to convert into an array containing each word length. (I know, this is not the kind of complex rocket science you usually need to execute for complex applications, but understanding how it works in this simple case will help you add real value to your code apply it in case).
You may already know how to use the for
loop on an array to do what I just described. It might look like this:
var animals = ["cat","dog","fish"]; var lengths = []; var item; var count; var loops = animals.length; for (count = 0; count < loops; count++) { item = animals[count]; lengths.push(item.length); } console.log(lengths); //[3, 3, 4]
All we did was define some variables: an array called animals
that contains our words; an empty array called lengths
that would contain the output of our operation; and a The variable of item
is used to temporarily store each item we will operate in each loop of the array. We optimize our for
loop with a temporary internal counter variable and a loops
variable. We then iterate over each item up to the for
array length. For each item, we calculate its length and push it into the animals
array. lengths
Note: We can say that we can do this more concisely by directly pushing the length of to the animals[count]
array without intermediate assignments. This will save us some code, but will also make the code less readable, even for this very simple example. Again, to make it more efficient, but less straightforward, we can initialize our lengths
array to animals
using the known lengths
array length and then insert the item by index instead of using new Array(animals.length)
. It all depends on how you will use the code in the real world. push
, it will appear clumsy to do so. map()
to deal with this: map()
var animals = ["cat","dog","fish"]; var lengths = animals.map(function(animal) { return animal.length; }); console.log(lengths); //[3, 3, 4]
array variable again. However, the only other variable we declare is animals
, which we assign directly to the result of mapping anonymous inline functions to each element of the lengths
array. This anonymous function performs an operation on each animal, returning the length. As a result, animals
becomes an array with the same length as the original lengths
array, containing the length of each word. animals
A few points to note about this method. First, it is much shorter than the original method. Second, we have to declare much fewer variables. The fewer variables, the less noise there will be in the global namespace, and if other parts of the same code use variables of the same name, the less chance of conflict. Furthermore, our variables do not need to change their value from beginning to end. As you dive into functional programming, you will appreciate the graceful ability of using constants and immutable variables, and it is not too late to start learning now.
Another advantage of this approach is that we have the opportunity to improve its versatility by separating named functions, thereby generating cleaner code in the process. Anonymous inline functions can look messy and make code reuse more difficult. We can define a function called getLength()
and use it in the context in this way:
var animals = ["cat","dog","fish"]; var lengths = []; var item; var count; var loops = animals.length; for (count = 0; count < loops; count++) { item = animals[count]; lengths.push(item.length); } console.log(lengths); //[3, 3, 4]
Look at how clean this looks? Just taking mappings as part of your toolkit can take your code to a whole new functional level.
Interestingly, by adding mapping functionality to array objects, ECMAScript 5 turns the basic array type into a complete functor, making functional programming easier for us all to use.
According to the classic functional programming definition, functors meet three conditions:
This is a topic you can discuss at your next JavaScript meeting.
If you want to learn more about functors, check out this amazing video by Mattias Petter Johansson.
Use Reduce
Thereduce()
method is also a new method in ECMAScript 5, which is similar to map()
, except that it does not generate another functor, but generates a single result, which can be of any type. For example, suppose you want to take the sum of the lengths of all the words in the animals
array as a number. You may start with:
var animals = ["cat","dog","fish"]; var lengths = animals.map(function(animal) { return animal.length; }); console.log(lengths); //[3, 3, 4]
After defining the initial array, we create a variable total
for the run total, initially set to zero. We also created a variable item
to save each iteration of the animals
array when it traversing the for
loop, and a variable count
for loop counters, and a loops
variable to optimize our iterations. Then, we run a for
loop to iterate over all words in the animals
array and assign each word to the item
variable. Finally, we add the length of each item to our total.
Again, this approach has no technical problems. We start with an array and finally get a result. However, using the reduce()
method, we can make this process more direct:
var animals = ["cat","dog","fish"]; var lengths = []; var item; var count; var loops = animals.length; for (count = 0; count < loops; count++) { item = animals[count]; lengths.push(item.length); } console.log(lengths); //[3, 3, 4]
What happens here is that we are defining a new variable total
and assigning it to the result of reducing the animals
array using two parameters: an anonymous inline function and an initial run total value zero. Reduction will traverse each item in the array, execute the function on that item, and add it to the run total passed to the next iteration. Here our inline function has two parameters: the run sum and the words currently being processed from the array. This function adds the current value of total
to the length of the current word.
Note that we set the second parameter of reduce()
to zero, which indicates that total
will contain a number. Without the second parameter, the reduce
method will still work, but the result is not necessarily the result you expect. (Try it and see what logic is used by JavaScript when running totals are omitted.)
Since the definition of anonymous inline functions is integrated when calling the reduce()
method, this may seem a little more complicated than it needs to be. Let's do this again, but let's first define a named function instead of using an anonymous inline function:
var animals = ["cat","dog","fish"]; var lengths = animals.map(function(animal) { return animal.length; }); console.log(lengths); //[3, 3, 4]
This one is a little longer, but it is not always a bad thing to grow. Viewing it this way should make what happens in the reduce
method a little clearer.
reduce()
method has two parameters: a function applied to each element in the array, and an initial value used to run the total. In this case, we pass the name of a new function named addLength
and the initial value of the run total zero. We created the addLength()
function so that it also accepts two parameters: the run sum and the string to be processed.
Conclusion
Developing the habit of using map()
and reduce()
regularly will provide you with alternatives to make your code more concise, more general, easier to maintain, and pave the way for you to use more functional JavaScript technologies the way.
map()
and reduce()
methods are just two of the new methods added to ECMAScript 5. Most likely, the improvements in code quality and developer satisfaction you see today will far outweigh any temporary impact on performance. Use functional techniques to develop and measure impact in the real world before deciding whether map()
and reduce()
are suitable for your application.
This article was reviewed by Panayiotis Velisarakos, Tim Severien and Dan Prince. Thanks to all SitePoint peer reviewers for getting SitePoint content to its best!
Frequently Asked Questions about Map-Reduce in Functional JavaScript (FAQ)
In JavaScript, Map and Reduce are both higher-order functions that act on arrays. The Map function is used to create a new array by applying the function to each element of the original array. It does not modify the original array, but returns a new array. On the other hand, the Reduce function is used to simplify arrays into single values. It applies the function in order to each element of the array so that it can be reduced to a single output value.
The Map function in JavaScript works by creating a new array from an existing array. It does this by applying the specified function to each element in the original array. The function is called once in order for each element in the array. The result is a new array containing the result of a function call.
The Reduce function in JavaScript works by applying the function in order to each element in the array so that the array can be reduced to a single output value. The output value is the cumulative result of the function call. This function accepts two parameters: the accumulator and the current value. The return value of the accumulator accumulating function call.
Yes, you can use Map and Reduce in JavaScript. In fact, they are often used together in functional programming. You can use the Map function to convert each element in an array and then use the Reduce function to combine the converted elements into a single output value.
Map and ForEach are both higher-order functions that act on arrays in JavaScript. The main difference between them is that Map creates a new array by applying a function to each element of the original array, while ForEach applies to each element of the array to get its side effects. ForEach does not return a new array.
You can use the Map function in JavaScript to convert an array by applying the function to each element of the array. The function is called once in order for each element in the array. The result is a new array containing the result of a function call.
You can use the Reduce function in JavaScript to combine elements of an array into a single output value. The function is applied in order to each element in the array, and the output value is the cumulative result of the function call.
Map functions in JavaScript are often used to convert arrays by applying functions to each element of an array. Some common use cases include converting strings to numbers, changing the case of strings, and extracting properties from objects.
Reduce functions in JavaScript are usually used to combine elements of an array into a single output value. Some common use cases include summing numbers, finding maximum or minimum values, and concatenating strings.
You can debug Map or Reduce functions in JavaScript by using the console.log
statement in the function to display the values of variables and expressions. You can also pause execution using the debugger
statement and check the values of variables and expressions in the developer tools of the web browser.
The above is the detailed content of Using Map and Reduce in Functional JavaScript. For more information, please follow other related articles on the PHP Chinese website!