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

Source: Internet
Author: User
The built-in function is actually a built-in function, and the reduce function is an array method that appears in the ECMAScript5 specification. In my daily work, I believe there are not many use cases. This article gives you a detailed introduction to the application of function reduce and multiple overlays. If you need them, you can refer to them for reference, let's take a look. Preface

Generally, the logic that can be implemented through the reduce method can be implemented in disguise through the forEach method. Although it is unclear how the browser's js engine implements these two methods at the C ++ layer, however, it is certain that the reduce method 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

The reduce method has two parameters. The first parameter is a callback parameter used for operations on Array items. The second parameter is the input initial value, which is used for operations on a single array item. It should be noted that the return values of the reduce method are not arrays, but operations such as initial values after superposition.

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

We can see that the reduce function is constantly superimposed based on the initial value 0 to achieve the simplest sum.

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

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. In the preceding example, the initial value {sum: 0} 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 to encapsulate the first callback parameter of the reduce function as an array. Each function in the array overlays and completes the reduce operation. All processes are managed and initial parameters are passed through a manager function.

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

The above is the implementation of the manager function. It requires the aggregcers object as the parameter and returns a callback type function as the first parameter of reduce. In this function, multi-dimensional overlay (Object. keys () is executed ()).

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.

For more details about the application of the built-in reduce function in Javascript, please follow the PHP Chinese network!

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.