Using Array.prototype.reduce () to reduce conceptual boilerplate for problems on Arrays

Source: Internet
Author: User

The following is transferred from Freecodecamp:using Array.prototype.reduce () to reduce conceptual boilerplate for problems on ArraysUsing Array.prototype.reduce () to reduce conceptual boilerplate for problems on arrays translation: Use Array.prototype.reduce () Can reduce tedious problems such as array looping

  We know that the For loop is not refined in JavaScript. It will let you take up your time: cache occupancy, naming, and logic errors. Also, when writing code, there is an error in the asynchronous process code without closing the loop clock. See: Asynchronous Process inside a javascript for loop

This headline has already told us that you can use the reduce () method to solve an array-related problem instead of using a for loop or a while loop. If you want to continue reading: First you need to know what is "recursive" and some of the more useful array methods Array.prototype.map() orArray.prototype.filter()。

Practice is greater than genuine knowledge. Let's see how we get used to using reduce (). Before you learn, make sure you're here to learn to solve problems, not a quick glance.

Can I Reduce any array-related problem? Can i solve any problems related to arrays?

  Yes, I can! In fact, not only can solve the problem of array related, as long as he is a problem, can solve. For example, create a very common link address title: Slug URL, headline from news, blogs, and even question and answer forums.

function Createslug (str) {  return str.split (""). Reduce (function(prev, next) {     return Prev.concat ([Next.tolowercase ()]);//that's the core of the functionality we want.  }, [])  . Join ("-");}

Test yourself on the console, such as "Leo Finally Wins a freaking oscar!" :

leo-finally-wins-a-freaking-oscar!
But I don't understand Reduce at all! I don't even know reduce!!.

  Well, don't be afraid! In the next few minutes, you are about to become a reduce ninja.

There are three things you need to know about each JavaScript function to understand how the function works:

    • The input
    • The output
    • The execution context

  Yes, I can see you open the official MDN document in the New tab page! Never mind, read this first. I'm serious, it's not a joke.

Array.prototype.reduce () has two parameters: the callback function and the initial value are input parameters. (The initial value is very important.) Many developers forget to provide the initial values correctly and finally screw up their code).

Arr.reduce (function () {}, InitialValue);//Suppose Arr is a set of random arrays.

  Now, let's take a closer look at the callback function, the first parameter of reduce (), which requires two parameters. In the official documentation, the two parameters of these two are called Prev and next. Personally, I don't think the names of the two parameters represent the original meaning of this parameter.

I call the first parameter of the callback function ' ACC ', which represents the cumulative value (accumulated value); ' Item ', which represents the currently accessed value. So, our reduce () is like this:

Arr.reduce (function/**/}, InitialValue);

  As we mentioned earlier, reduce () transfers a function as an accumulator. Let's see how the values of these ' ACC ' and ' item ' will change.

var arr = [];arr.reduce (ACC, item) {   0);

Performing the above will give you this as output in the browser or node console:

0 10undefined 20undefined 30undefined 60

  Note the numbers of these outputs, as well as the numeric elements of the array [10, 20, 30, 60]. In fact, reduce () prints out the elements of the array.

Therefore, we can infer that reduce () requires your custom callback and executes each element of the array. While doing so, it makes the current item available for the custom callback for the ' item ' parameter.

But what about ACC? We see that, in addition to the first line, when ' item ' = 10, it is ' undefined '. In the first line, corresponding to the first iteration of iteration, it has the same value as the initial value initialvalue,0.

In short, our ' ACC ' is the accumulator, not the value being added! But how do we accumulate? Let's try to execute:

var arr = [];arr.reduce(ACC, item) {   Console.log (ACC, item); c7/>return0);

This time, the output changes:

0 100 200) 300 60

As you can see, ' ACC ' will keep the value unchanged. It is expected that we do not change the value of ' ACC ' in the custom callback. We return any reduce () make available in a given iteration.

But we realize what, ' ACC ' is the current duplicate value, and will return the value from the custom callback from the previous redo work. Finally, the final value of the returned ' ACC ' will be reduce () after the repeat work is finished.

This makes only one important part in our understanding-the value of the execution context, or ' this '! So, we again approach our friend, JS console and execute:  

var arr = [Ten, +, +,];arr.reduce (function(ACC, item) {   this) ;    return  0);

  If in strict mode, use this:

var arr = [Ten, +, +,];arr.reduce (function(ACC, item) {   this) ;    return  0);

I have bound the ARR array itself, but you can set it to any object in your environment.

Understanding reduce understanding Reduce

Let's summarize the simple reference to the reduce function:

    • Reduce reduces the need for a custom callback as its first parameter, and some initial values as the second parameter.
    • It is important that we do not forget the second parameter, the initial value, which we explicitly set in using it.
    • The input parameters of the custom callback function are the cumulative value ' ACC '; and the current item of the array, ' item '.
    • In the current iteration, the value of ' ACC ' in the next iteration will return a value in the callback.
    • The important point of using reduce () is to properly form ' ACC ', which returns the final function call.

Using Reduce

Let's start with a simple array operation and find the largest value in the array. For the sake of brevity, I assume this is an array of integers.

In order to form a solution, we need to consider how to form the ' ACC ' reduce let us callback and iterate over the array. An idea that I think is useful is to think of loop-invariants. We want to think of a square method, no matter what the size or content of the array, ' ACC ' should always be the maximum value.

My array is [20, 50, 5, 60]. After two iterations, ' item ' will be 5, ' ACC ' should be max (20, 50) = 50.

var arr = [5,];arr.reduce (ACC, item) {  return  0);

It may easily be rewritten as follows, with the principle of functional programming:

var arr = [5,0);

Using Array.prototype.reduce () to reduce conceptual boilerplate for problems on Arrays

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.