Application of the built-in function reduce in JavaScript _javascript tips

Source: Internet
Author: User

Objective

In general, the reduce logic can be implemented through the method forEach to disguise the implementation, although it is not clear how the browser JS engine in the C + + level to implement the two methods, but it is certain that the reduce method must also exist array traversal, It is not known whether the implementation details are optimized for the operation and storage of array items.

The application of the reduce method of array

reduceThe method has two parameters, the first argument is one callback , the action for the array item, and the second parameter is the incoming initial value, which is used for the operation of a single array item. It should be noted that the reduce method return value is not an array, but rather an overlapped operation of the form such as the initial value.

The most common scenario for the reduce method is overlay.

var items = [ten, 1000];

Our reducer function
is var reducer = function Add (sumsofar, item) {return Sumsofar + item;};

Does the job
var total = items.reduce (reducer, 0);

Console.log (total); 1130

It can be seen that the reduce function is based on the initial value of 0, constantly stacking, complete the simplest sum of the implementation.

As mentioned earlier, the reduce return result type of the function is the same as the incoming initial value, and the initial value in the previous instance is of number type, and the original value can also be of object type.

var items = [ten, 1000];

Our reducer function
var reducer = function Add (sumsofar, item) {
 Sumsofar.sum = sumsofar.sum + item;
 return sumsofar;
};

Does the job
var total = items.reduce (reducer, {sum:0});

Console.log (total); {sum:1130}

Multiple overlay

Use the reduce method to complete multidimensional data overlays. As the initial value in the example above {sum: 0} , this is only a dimension operation, if the superposition of multiple attributes is involved, for example {sum: 0,totalInEuros: 0,totalInYen: 0} , the corresponding logic needs to be processed.

In the following method, a divide-and-conquer method is used to reduce encapsulate the first parameter of a function callback as an array, stacked separately by each function in the array and completing the reduce operation. Everything through a manager function to manage the process and to pass the initial parameters.

var managereducers = function (reducers) {return
 function (state, item) {return
 Object.keys (reducers). reduce (
  function (nextstate, key) {
  Reducers[key] (state, item);
  return state;
  },
  {}
 );
 }
;

Above is manager the implementation of the function, which requires the Reducers object as a parameter and returns a callback type of function as reduce the first argument. Inside the function, the multidimensional overlay work () is performed Object.keys() .

Through this idea of divide and conquer, we can complete the superposition of multiple attributes of target object, the complete code is as follows:

var reducers = { 
 totalineuros:function (state, item) {return
 State.euros + = Item.price * 0.897424392;
 },
   
    totalinyen:function (State, item) {return
 State.yens + + = Item.price * 113.852;
 }
;

var managereducers = function (reducers) {return
 function (state, item) {return
 Object.keys (reducers). reduce (
  function (nextstate, key) {
  Reducers[key] (state, item);
  return state;
  },
  {}
 );
 }
;

var bigtotalpricereducer = managereducers (reducers);

var initialstate = {euros:0, yens:0};

var items = [{price:10}, {price:120}, {price:1000}];

var totals = items.reduce (Bigtotalpricereducer, initialstate);

Console.log (totals);
   

Summarize

The above is JavaScript in the built-in function reduce the full content of the application, I hope the content of this article for everyone's study or work can help, if there is doubt you can message exchange.

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.