JavaScript Learning notes: array reduce () and reduceright () methods

Source: Internet
Author: User
Tags drupal

Many times you need to accumulate an array of items to get a value (for example, sum). If you come across a similar problem, what do you think of the method? Would it be like me to think about using for or while looping, iterating over arrays, adding their values in turn. Like what:

var arr = [1,2,3,4,5,6];Array.prototype.sum = function (){ var sumResult = 0; for (var i = 0; i < this.length; i++) { sumResult += parseInt(this[i]); } return sumResult;}arr.sum(); // 21

Or

var arr =  [1,2,3,4,5,6];Array.prototype.sum = function () { var sumResult = 0; var i = this.length; while (i--) { sumResult += parseInt(this[i]); } return sumResult;}arr.sum(); // 21

So are they the best solution? Let's take a look at the time they're consuming.

To test the performance of the for and while loops for array summationvar arr = [1,2,3,4,5,6];For Loop Console.time ("Forloop");array.prototype.forloop = function  () {for (var i = 0; i < 10000; i++) {var sumresult = 0; for (var j = 0; j <  This.length; J + +) {Sumresult + = parseint (this[j]);}} return sumresult;} Arr.forloop (); Console.log ( ' final value: ' + arr.forloop ()); //21console.timeend ( "Forloop"); //54.965ms             

Let's take a look at while the time of the loop:

var Arry = [1,2,3,4,5,6];console.time ("Whileloop");array.prototype.whileloop = function  () {for (var i = 0; i < 10000; i++) {var sumresult = 0; for (var j = 0; j <  This.length; J + +) {Sumresult + = parseint (this[j]);}} return sumresult;} Arry.whileloop (); Console.log ( ' final value: ' + arry.whileloop ()); //21console.timeend ( "Whileloop"); //53.056ms             

Look at the comparison results.

Loop Type final Value (and) Time Taken
For 21st 54.965ms
While 21st 53.056ms

Note: [1,2,3,4,5,6] the array 10000 is incremented for the secondary loop.

Although the above for and while all can achieve the desired effect, but there is no better solution in JavaScript? The answer is yes, in JavaScript (Esmascript 5) provides two additional arrays of methods reduce() and reduceRight() , the two arrays iterate over all array items of the algebraic group, and then return a final value. The next content, mainly to learn these two methods.

reduce()Method

reduce()Method receives a function callbackfn as an accumulator (accumulator), and each value (from left to right) in the array begins to merge and eventually a value.

Grammar
array.reduce(callbackfn,[initialValue])

reduce()The method receives a callbackfn function that contains four parameters:

function callbackfn(preValue,curValue,index,array){}
    • preValue: The value returned by the last call to the callback, or the provided initial value (InitialValue)
    • curValue: Array items that are currently being processed in the array
    • index: The index value of the current array item in the array
    • array: reduce() An array of call methods

and initialValue as callbackfn the first argument to call the function first.

reduce()The method executes the callback function sequentially for each element in the callbackfn array, not including the element that was deleted or never assigned to it, and accepts four parameters: the initial value (or the return value of the last callback function), the current element value, the current index, and reduce() the array of calls.

The first time the callback function executes, preValue and curValue can be a value, if it is initialValue provided at the reduce() time of invocation, then the first is preValue equal to and initialValue curValue equal to the first value in the array; initialValue preValue equals the first value in the array, ' Curvalue equals the second value in the array.

Consider an example:

var arr = [0,1,2,3,4];arr.reduce(function (preValue,curValue,index,array) { return preValue + curValue;}); // 10

The callback function in the example is executed four times, with each parameter and the value returned as follows:

prevalue curvalue index array return value
First time callback 0 1 1 [0,1,2,3,4] 1
Second callback 1 2 2 [0,1,2,3,4] 3
Third callback 3 3 3 [0,1,2,3,4] 6
Fourth time callback 6 4 4 [0,1,2,3,4] 10

The above example reduce() method does not provide initialValue an initial value, and then, in the example above, slightly modifies it to provide an initial value, which is a value of 5 . This time the reduce() method executes five callbacks, each time the parameter and the value returned are as follows:

var arr = [0,1,2,3,4];arr.reduce ( function (Prevalue,curvalue,index,array) {return prevalue + Curvalue;}, 5); //15              
prevalue curvalue index array return value
First time callback 5 0 0 [0,1,2,3,4] 5
Second callback 5 1 1 [0,1,2,3,4] 6
Third callback 6 2 2 [0,1,2,3,4] 8
Fourth time callback 8 3 3 [0,1,2,3,4] 11
Fifth time callback 11 4 4 [0,1,2,3,4] 15

This way, needless to say, you should know that you can use reduce() the function of implementing array summation. Such as:

var arr = [1,2,3,4,5, 6]; array.prototype.sum = < span class= "keyword" >function  () { var sumresult = 0; return this.reduce (< Span class= "function" >function   (Prevalue, curvalue) {return sumresult = Prevalue + curvalue;}); return sumresult;} Arr.sum (); //             

Back in front of the article, let's see reduce() how long it takes to use the method to sum the arrays:

var arr = [1,2,3,4,5,6];console.time ("Ruduce");Array.prototype.ruduceSum =function () {for (var i = 0; i < 10000; i++) { return this.reduce (function  (Prevalue, curvalue) { return prevalue + curvalue;});}} Arr.ruducesum (); Console.log (' final value: ' + arr.ruducesum ()); //21console.timeend ("ruduce"); //0.417ms                

Also look at the comparison of time spent:

Loop Type final Value (and) Time Taken
For 21st 54.965ms
While 21st 53.056ms
Reduce 21st 0.417ms

In the Chrome browser, each execution of the data will be slightly different, but you can clearly see that the sum of the array of the reduce() time is the shortest.

reduceRight()Method

reduceRight()The functions and functions of the method are the same, but the array items in the array are added reduce() reduceRight() forward from the end of the array.

reduceRight()The first time a callback function callbackfn is called, prevValue and curValue can be one of two values. If reduceRight() a parameter is supplied when called initialValue , it is prevValue equal initialValue to, equal to, the curValue last value in the array. If no argument is supplied initialValue , it is prevValue equal to the last value of the array, curValue equal to the second-lowest value in the array.

See Example:

var arr = [0,1,2,3,4];arr.reduceRight(function (preValue,curValue,index,array) { return preValue + curValue;}); // 10

The callback will be called four times, and the parameters and return values of each call are as follows:

prevalue curvalue index array return value
First time callback 4 3 3 [0,1,2,3,4] 7
Second callback 7 2 2 [0,1,2,3,4] 9
Third callback 9 1 1 [0,1,2,3,4] 10
Fourth time callback 10 0 0 [0,1,2,3,4] 10

If you provide an initial value initialValue of 5 :

var arr = [0,1,2,3,4];arr.reduceRight(function (preValue,curValue,index,array) { return preValue + curValue;}, 5); // 15

The callback will be called five times, the parameters of each call and the values returned are as follows:

prevalue curvalue index array return value
First time callback 5 4 4 [0,1,2,3,4] 9
Second callback 9 3 3 [0,1,2,3,4] 12
Third callback 12 2 2 [0,1,2,3,4] 14
Fourth time callback 14 1 1 [0,1,2,3,4] 15
Fifth time callback 15 0 0 [0,1,2,3,4] 15

Similarly, you can add a sum to an array, or you can use the reduceRight() method:

var arr = [1,2,3,4,5,6];console.time ("Ruduceright");Array.prototype.ruduceRightSum = function () {for (var i = 0; i < 10000; i++) { return this.reduceright Ction (Prevalue, curvalue) { return prevalue + curvalue;});}} Arr.ruducerightsum (); Console.log (' final value: ' + arr.ruducesum ()); //21console.timeend ("ruduceright"); //5.725ms                
Summarize

reduce()and reduceRight() Two method functions are similar, you can let the array call a callback function callbackfn as an accumulator. In fact, according to this callback function, you can implement different functions, for example, to find a combination of array items, merging multiple arrays into an array, and so on. Even with the array of other methods you can do more processing of the functions. If you are interested, do not attempt to imitate one or two.

The beginner learns the note, if has the wrong, also hoped the expert directs. If there is a misunderstanding, but also hope that a lot of understanding.

Desert commonly used nickname "Desert", W3cplus founder, currently employed in the hand Amoy. One of the core members of the Drupal community in China. HTML5, CSS3 and sass, such as the front-end scripting language has a very deep understanding and rich practical experience, especially focus on CSS3 research, is the earliest research and use of CSS3 technology of a group of people. CSS3, Sass and Drupal Chinese evangelists. 2014 published "Graphic CSS3: Core technology and practical case".

If you need to reprint, please indicate the source: http://www.w3cplus.com/javascript/array-part-8.html

JavaScript Learning notes: array reduce () and reduceright () methods

Related Article

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.