Home > Web Front-end > JS Tutorial > body text

Usage and tips of the array Reduce() function in JavaScript

巴扎黑
Release: 2017-08-21 10:03:46
Original
1817 people have browsed it

reduce executes the callback function in sequence for each element in the array, excluding elements that are deleted or never assigned a value in the array. Next, I will share with you the detailed explanation and advanced techniques of the JS array Reduce() method through this article. Let’s take a look at it

Basic concepts

##reduce( ) method receives a function as an accumulator, and each value in the array (from left to right) starts to be reduced to one value.

reduce executes the callback function in sequence for each element in the array, excluding elements that are deleted or never assigned a value in the array, and accepts four parameters: initial value (or the return value of the last callback function) , the current element value, the current index, the array in which reduce is called.

Syntax:


arr.reduce(callback,[initialValue])
Copy after login

  • callback (execute each value in the array function, containing four parameters)

  • previousValue (the value returned from the last callback call, or the provided initial value (initialValue))

  • currentValue (the currently processed element in the array)

  • index (the index of the current element in the array)

  • array (call reduce array)

  • initialValue (as the first parameter of the first callback call.)

Simple application

Example 1:


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

It can be seen that the reduce function continuously superposes based on the initial value 0, which is the simplest completion The realization of the sum.

The return result type of the reduce function is the same as the passed in initial value. In the previous example, the initial value was of type number. Similarly, the initial value can also be of type object.

Example 2:


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

Advanced application

You can use the reduce method Complete multi-dimensional data overlay. As shown in the above example, the initial value {sum: 0} is only a one-dimensional operation. If it involves the superposition of multiple attributes, such as {sum: 0, totalInEuros: 0, totalInYen: 0}, corresponding logic is required. deal with.

In the following method, the divide and conquer method is adopted, that is, the callback, the first parameter of the reduce function, is encapsulated into an array, and each function in the array is independently superimposed and completes the reduce operation. Everything is managed through a manager function and initial parameters are passed.


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

The above is the implementation of the manager function. It requires reducers objects as parameters and returns a callback type function as the first parameter of reduce. Within this function, multi-dimensional superposition work (Object.keys()) is performed.

Through this divide-and-conquer idea, the simultaneous superposition of multiple attributes of the target object can be completed. 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);
Copy after login

Here is an example:

The final grade of a certain student is expressed as follows


var result = [
  {
    subject: 'math',
    score: 88
  },
  {
    subject: 'chinese',
    score: 95
  },
  {
    subject: 'english',
    score: 80
  }
];
Copy after login

How to find the total grade of the student?


var sum = result.reduce(function(prev, cur) {
  return cur.score + prev;
}, 0);
Copy after login

Assuming that the student is punished for violating discipline and has a total score of 10 points deducted, you only need to set the initial value to -10.


var sum = result.reduce(function(prev, cur) {
  return cur.score + prev;
}, -10);
Copy after login

Let’s make this example a little more difficult. If each subject has a different weight in the student's total score, 50%, 30%, and 20% respectively, how should we find the final weighting result?

The solution is as follows:


var dis = {
  math: 0.5,
  chinese: 0.3,
  english: 0.2
}
var sum = result.reduce(function(prev, cur) {
  return cur.score + prev;
}, -10);
var qsum = result.reduce(function(prev, cur) {
  return cur.score * dis[cur.subject] + pre;
}, 0)
console.log(sum, qsum);
Copy after login

Look at another example, how to know the contents of a string How many times does each letter appear?


var arrString = 'abcdaabc';
arrString.split('').reduce(function(res, cur) {
  res[cur] ? res[cur] ++ : res[cur] = 1
  return res;
}, {})
Copy after login

Since the type initial value of the superposition result can be set through the second parameter, reduce at this time is no longer just an addition, we can use it flexibly To perform various type conversions, such as converting arrays into objects according to certain rules, or converting one form of array into another form of array, you can try it yourself.


[1, 2].reduce(function(res, cur) { 
  res.push(cur + 1); 
  return res; 
}, [])
Copy after login

In the source code of koa, there is an only module. The entire module is a simple object that returns the reduce method operation:


var only = function(obj, keys){
 obj = obj || {};
 if ('string' == typeof keys) keys = keys.split(/ +/);
 return keys.reduce(function(ret, key){
  if (null == obj[key]) return ret;
  ret[key] = obj[key];
  return ret;
 }, {});
};
Copy after login

Through the understanding of the reduce concept, this module mainly wants to create and return an object object of the keys existing in the obj object.


var a = {
  env : 'development',
  proxy : false,
  subdomainOffset : 2
}
only(a,['env','proxy'])  // {env:'development',proxy : false}
Copy after login

The above is the detailed content of Usage and tips of the array Reduce() function in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template