Detailed description of the application of the built-in reduce function in Javascript, javascriptreduce

Source: Internet
Author: User

Detailed description of the application of the built-in reduce function in Javascript, javascriptreduce

Preface

In general, you can usereduceThe method implementation logic can be passed throughforEachAlthough it is unclear how the browser's js engine implements these two methods in the C ++ layerreduceThe method certainly also has array traversal. It is unknown whether the operation and storage of array items are optimized in specific implementation details.

Application of the reduce method of Arrays

reduceThe method has two parameters. The first parameter iscallbackIs used for operations on Array items. The second parameter is the input initial value, which is used for operations on a single array item. Note that,reduceThe Return Value of the method is not an array, but an operation that forms the initial value after Being superimposed.

The most common scenario of the reduce method is superposition.

var items = [10, 120, 1000];// our reducer functionvar reducer = function add(sumSoFar, item) { return sumSoFar + item; };// do the jobvar total = items.reduce(reducer, 0);console.log(total); // 1130

As you can see,reduceThe function is constantly superimposed based on the initial value 0 to implement the simplest sum.

As mentioned above,reduceThe return result type of the function is the same as the input initial value. The initial value in the previous instance isnumberType. Similarly, the initial value can also beobjectType.

var items = [10, 120, 1000];// our reducer functionvar reducer = function add(sumSoFar, item) { sumSoFar.sum = sumSoFar.sum + item; return sumSoFar;};// do the jobvar total = items.reduce(reducer, {sum: 0});console.log(total); // {sum:1130}

Multiple Overlays

The reduce method can be used to complete multi-dimensional data superposition. Initial Values in the preceding example{sum: 0} This is only a dimension operation. If multiple attributes are involved, for example{sum: 0,totalInEuros: 0,totalInYen: 0} , The corresponding logic is required for processing.

In the following method, the divide and conquer method is used, that isreduceThe first parameter of the function.callbackEncapsulated as an array. Each function in the array is superimposed and completed separately.reduceOperation. Everything goes through onemanagerFunction to manage processes and pass 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 ismanagerFunction implementation, which requires the javascers object as the parameter and returnscallbackType function,reduce. In this function, multi-dimensional superposition is performed (Object.keys() ).

With this sub-governance idea, multiple attributes of the target object can be superimposed at the same time. 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);

Summary

The above is all the content of the reduce application of the built-in function in Javascript. I hope the content in this article will be helpful for your study or work. If you have any questions, please leave a message.

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.