Using the map and reduce methods in JavaScript functional programming

Source: Internet
Author: User
Tags javascript array

Everyone is talking about the amazing new features that workflows supports in ECMASCRIPT6, so it's easy to forget that ECMAScript5 gives us some great tools to support functional programming in JavaScript, These tool methods we can now use. In these function methods, the map () method and the reduce () method are mainly based on the JavaScript array object.

If you're not using the map () and reduce () methods now, it's time to start using them. The vast majority of JavaScript development platforms today are ECMAScript5 with innate support. Using the map method and the reduce method can make your code more concise, easier to read and easier to maintain, and take you on the road toward more concise feature development.

Performance: a warning

Of course, the legibility and maintainability of your code has to be balanced between the two when the real situation needs to keep improving performance. Today's browsers use more cumbersome traditional techniques such as for loops to perform more efficiently.

The way I write code is usually to put the readability and maintainability in the first place of writing code, and then if I find that the code is running out of order in the real world, then I'm going to optimize the code to improve performance. It is difficult to optimize code prematurely, and this optimization can lead to difficulties in writing code later.

It is worth considering that using methods such as map () and reduce () in the JavaScript engine can better improve the performance of the code, rather than relying on future browsers to optimize for performance. Unless I'm hitting the wall on a performance issue, I prefer to write the code happily, but in case I need them I'm always ready to make adjustments to keep the code performing, even though it makes my code less appealing.

Using the Map method

Mapping is a basic functional programming technique that works on all elements in an array and other arrays created with the same length and with the transformed content.

To make the argument a little more specific, I came up with a simple use example. For example, imagine that you have an array with character data in it, and you need to convert them into another array that contains the length of each character data. (I know, that's not as complicated as rocket science, it's something you often have to do to write complex applications, but understanding how it works in a simple example like this will help you use it, in which case you can add real data values to it in your code).

You might know what I just described. How to use a For loop on an array. It may look like this:

var animals = ["Cat", "dog", "fish"];var lengths = [];var item;var Count;var loops = animals.length;for (count = 0; Count &l T Loops count++) {  item = Animals[count];  Lengths.push (item.length);} Console.log (lengths); [3, 3, 4]

All we need to do is define a small number of variables: An array named animals contains the character data we need, a null array named lengths will be used in the future to contain the length of the data output of our operation array, and a variable called item, This variable is used to temporarily store array items that we need to manipulate each time the loop iterates through the array. We define a for loop that has an internal variable and a loop variable to initialize our for loop. Then we iterate over each item until the iteration's array length equals the length of the animals array. Each cycle we calculate the character length of the iteration and save it in the lengths array.

Note: It is important to discuss that we can write the above code more succinctly, do not need the item variable, and directly put the length of Animals[count] into the lengths array, so that the intermediate conversion process is not required. Doing this can save us a little bit of code space, but it also makes our code a little hard to read, even in this very simple example. Similarly, in order to make the code more efficient and less straightforward, we might use the known animals array length to initialize our lengths array in the way of the new Array (animals.length). The option data length is then inserted through the index instead of using the push method. It depends on how you are going to use the code in the real world.

There is no technical error in this way of implementation. It can be used in any standard JavaScript engine, and it can do a good job. Once you know how to use the map () method, it's a bit clumsy to do it this way.

Let me show you how to use the map () method to implement the above code:

var animals = ["Cat", "dog", "fish"];var lengths = Animals.map (function (animal) {  return animal.length;}); Console.log (lengths); [3, 3, 4]

In this small example, we first create a animals variable for our array of animal types again. However, the other variables we need to declare are the lengths variables, and then we assign the value directly to the result of mapping an anonymous inline function to each element of the animals array.

The anonymous function executes the operation on each animal and then returns the character length of the animal. As a result, lengths becomes an array with the same length as the original animals array, and the array contains the length of each character.

There are some things to be aware of in this way. First, it is more concise than the code originally written. Second, we just need to declare fewer variables. Fewer variables mean less noise in the global namespace and less chance of collisions if other parts of the same code use the same variable name. Finally, our variables are not likely to change their values from head to toe. As you delve into functional programming, you'll appreciate the elegant ability to use constants and immutable variables, and it's not too early to start using them.

Another advantage of this approach is that we can simplify the code by putting code in a named function throughout the code, and have the opportunity to improve the versatility of writing code. Anonymous inline functions look a bit messy and make it more difficult to reuse code. We can define a function named GetLength () and use it as follows:

var animals = ["Cat", "dog", "Fish"];function getlength (word) {  return word.length;} Console.log (Animals.map (getlength)); [3, 3, 4]

See how concise the code looks like? Just mapping out the parts of your data to get your code to a whole new level of functionality.

What is a functor?

Interestingly, by adding a mapping to an array object, ECMAScript5 the basic array type into a complete functor, which makes functional programming easier for us.

According to the traditional function programming definition, a functor needs to meet three conditions:

    • 1. It holds a set of values.
    • 2. It implements a map function to manipulate each element.
    • 3. Its map function returns a functor of the same size.

This will be discussed over and over again at your next JavaScript party.

If you want to learn more about the functor, you can take a look at Mattias Petter Johansson recorded in this video.

Using the Reduce method

The reduce () method is also new in ECMAScript5, and it is similar to the map () method, except that no other functor is produced, and one result of the reduce () method is that it may be of any type. For example, imagine if you want all the character lengths in our animals array to be the result of a number and then the addition of each. You might do something like this:

var animals = ["Cat", "dog", "fish"];var total = 0;var Item;for (var count = 0, loops = animals.length; count < loops; co unt++) {  item = Animals[count];  Total + = Item.length;} Console.log (total); 10

After we define our initial array, we define a total variable for the run totals and set its initial value to 0. We also define a variable item to hold the iteration value of the animals array for each iteration of the for loop, and then define a count variable as a loop counter, and use these two variables to initialize our iterations. We then run the for loop to iterate through all the character data in the animals array, and each iteration saves the result of the iteration to the item variable. Finally, we add the length of each iteration to our total variable.

There is no technical error in this implementation. We start by defining an array, and then we end up with a result value. But if we use the reduce () method, we can make the above code simpler and clearer:

var animals = ["Cat", "dog", "fish"];var total = animals.reduce (function (sum, Word) {  return sum + word.length;}, 0); con Sole.log (total);

What happens here is that we define a new variable named Total, and assign the return value of the reduce method that executes the animals array object to it, there are two parameters in the reduce method: an anonymous inline function method, and the value of initialize total is 0. For each item in the array, the reduce () method executes, executes the function on that item of the array, adds it to the running total, and then the next iteration. Here our inline function method has two parameters: the running total, and the characters that are being fetched from the array that the current program is processing. This function adds the value of the current total to the length of the current word.

Note that we set the second parameter value of the reduce () method to 0, which determines that the total variable contains a numeric value. If you do not have a second parameter, the reduce method can still be executed, but the result will not be the one you expect. (You can try and see if you can figure out the programming logic used by JavaScript when the run totals are over.) )

That seems a little more complicated than it needs to be, because when you call the reduce () method, you need to synthesize the definition in an inline function. Let's do it again, but first let's define a named function function instead of using an anonymous inline function:

var animals = ["Cat", "dog", "fish"];var addlength = function (sum, Word) {  return sum + word.length;}; var total = animals.reduce (addlength, 0); Console.log (total);

This code is a little bit long, but the code is a bit long and not always bad. You should see it so that it makes the code clearer, just a little bit of a change in the reduce () method.

The reduce () method in the program has two parameters: a function that invokes each element in the array, and a run total initial value set for the totals variable. In this code example, we put a new function named Addlength and assign an initial value of 0 to the run total variable. In the previous line of code, we defined a function function called Addlength, which also requires two parameters: A current and a string to be processed.

Conclusion

Using the map () method and the reduce () method often will make your code more concise, more versatile, and more maintainable. They also pave the way for you to use more JavaScript functional function techniques.

The map () method and the reduce () method are only two of the new methods that are added into the ECMAScript5. From using them today you will understand that the improvement in code quality and the increase in developer satisfaction outweigh any temporary impact on performance. Before judging whether the map () method and the reduce () method are appropriate for your application, try to develop and measure its impact in your real world with functional function techniques before judging whether or not to use it.

Using the map and reduce methods in JavaScript functional programming

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.