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])
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
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}
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; }, {} ); } };
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);
var result = [ { subject: 'math', score: 88 }, { subject: 'chinese', score: 95 }, { subject: 'english', score: 80 } ];
var sum = result.reduce(function(prev, cur) { return cur.score + prev; }, 0);
var sum = result.reduce(function(prev, cur) { return cur.score + prev; }, -10);
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);
var arrString = 'abcdaabc'; arrString.split('').reduce(function(res, cur) { res[cur] ? res[cur] ++ : res[cur] = 1 return res; }, {})
[1, 2].reduce(function(res, cur) { res.push(cur + 1); return res; }, [])
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; }, {}); };
var a = { env : 'development', proxy : false, subdomainOffset : 2 } only(a,['env','proxy']) // {env:'development',proxy : false}
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!