JS Array High-order method reduce classic usage code share

Source: Internet
Author: User
Tags prev javascript array

Here are some snippets of code about the JavaScript array method that the individual collects and summarizes in the work, and reduce subsequent encounters with other scenarios that use this function will be added in succession, as a memo.

JavaScript array So many ways, why I have to take reduce a single approach, one reason is that I have not mastered this method enough to be free enough to do whatever it takes. On the other side, I also feel the immense charm of this method, which plays a magical role in many scenes.

Understanding reduce Functions

The reduce () method receives a function as an accumulator (accumulator), and each value (from left to right) in the array begins to shrink, resulting in a value.

Arr.reduce ([Callback, InitialValue])

See the following example:

Let arr = [1, 2, 3, 4, 5];//10 represents the initial value, p represents the cumulative value for each time, and at the first time for 10//if there is no initial value, then the first value of P is 1//at this point the cumulative result is 15let sum = Arr.reduce ((p, c) = = P + C, 10); 25//converted to ES5 is: var sum = arr.reduce (function (p, c) {Console.log (P); return p + C;}, 10);

Fragment One: Alphabet Games

Const ANAGRAMS = str = = {if (str.length <= 2) {  return str.length = = = 2? [STR, str[1] + str[0]: str; } return Str.split (""). Reduce ((ACC, letter, i) = = {  return Acc.concat (anagrams (str.slice (0, I) + str.slice (i + 1)). Map (val = letter + val)); }, []);} Anagrams ("abc"); What would be the result?

reduceResponsible for filtering out the first letter of each execution, and recursion is responsible for arranging the remaining letters.

Fragment Two: accumulator

Const SUM = arr = Arr.reduce ((ACC, val) = = acc + val, 0); sum ([1, 2, 3]);

Fragment Three: Counter

Const Countoccurrences = (arr, value)-Arr.reduce ((A, v) = = = = value, a + 1:a + 0, 0); countoccurrences ([1, 2 , 3, 2, 2, 5, 1], 1);

An array of loops, each encountering a value equal to the given value, plus 1, plus the subsequent result as the next initial value.

Fragment Four: function currying

The purpose of the function curry is to store the data and then execute it in the final step.

Const CURRY = (FN, arity = fn.length, ... args) =  arity <= args.length? fn (.... args): Curry.bind (null, FN, Arit Y, ... args); Curry (Math.pow) (2); Curry (Math.min, 3) (10) (50) (2);

By judging the parameters of the function to obtain the current function length (of course, you can also specify), if the argument is less than the current parameter, then continue to recursively below, while storing the last passed parameters.

Fragment five: Array flattening

Const Deepflatten = arr =  Arr.reduce ((A, V) = A.concat (Array.isarray (v)? Deepflatten (v): v), []);d Eepflatten ([1, [2, [3, 4, [5, 6]]]);

Fragment VI: Generate Fibonacci array

Const FIBONACCI = n = = Array (n). Fill (0). Reduce ((ACC, val, i) = Acc.concat (i > 1? acc[i-1] + acc[i-2]: i), []); Fibonacci (5);

Fragment Seven: Pipe processor

Const PIPE = (... funcs) = arg = Funcs.reduce (ACC, func) = Func (ACC), ARG);p ipe (btoa, x = X.touppercase ()) ("Test");

By processing the passed parameters, the processed data is then used as the parameters of the next function, so that the layers are passed down.

Fragment VIII: Middleware

Const DISPATCH = Action = = {Console.log (' action ', action); Return action;} Const MIDDLEWARE1 = dispatch = {return action = {  Console.log ("Middleware1");  Const RESULT = dispatch (action);  Console.log ("after Middleware1");  return result; }}const Middleware2 = dispatch = {return action = {  Console.log ("Middleware2");  Const RESULT = dispatch (action);  Console.log ("after Middleware2");  return result; }}const Middleware3 = dispatch = {return action = {  Console.log ("Middleware3");  Const RESULT = dispatch (action);  Console.log ("after Middleware3");  return result; }}const compose = Middlewares = Middlewares.reduce ((a, b) = args + A (b (args))) const Middlewares = [Middleware1 , Middleware2, Middleware3];const afterdispatch = Compose (middlewares) (dispatch), const Testaction = arg = {return {t ype: "Test_action", Params:arg};}; Afterdispatch (Testaction ("1111"));

reduxIn the classic composeThis method is used in the function to trigger the function execution when the action is actually initiated by layering the middleware. Fragment IX: Redux-actions processing fragments of state
Redux-actions/src/handleaction.jsconst handleaction = (type, reducer, defaultstate) = = {Const TYPES = type.tostring (); const [Nextreducer, Throwreducer] = [reducer, reducer];  return (state = defaultstate, action) = {const {type:actiontype} = action;  if (!actiontype | | types.indexof (actiontype.tostring ()) = = = 1) {return state; } return (Action.error = = = True Throwreducer:nextreducer) (State, action); }}//reduce-reducers/src/index.jsconst reducereducer = (... reducers) + {return (previous, current) = {reducers. Reduce (p, r) = R (P, current), previous); }}//redux-actions/src/handleactions.jsconst handleactions = (handlers, Defaultstate, {namespace} = {}) + = {//Reduc The flattened const flattenedreducermap of ers = Flattenreducermap (handles, namespace); The corresponding reducer processing method under each action is const REDUCERS = Reflect.ownkeys (flattenedreducermap). Map (Type = handleaction (Type, FL Attenedreducermap[type], defaultstate)); State of the processor, for the execution of the reducer const REDUCER = REDucereducers (... reducers); REDUCER trigger return (state = defaultstate, action) = reducer (State, action);}
fragment x: Data Processor
Const Reducers = {Totalineuros: (state, item) = {  return state.euros + = Item.price * 0.897424392;}, Totalinyen: (state, item) = {  return state.yens + = Item.price * 113.852;}; Const Managereducers = reducers = {return (state, item) = {  return Object.keys (reducers). Reduce ((nextstate, K EY) = {   Reducers[key] (state, item);   return state;  }, {})}}const Bigtotalpricereducer = Managereducers (reducers); Const Initialstate = {euros:0, yens:0 };const items = [{price:10}, {price:120}, {price:1000}];const totals = items.reduce (bigtotalpricereducer, initial State);
fragment 11: Object null value judgment
Let school = {name: ' Hope Middle School ', created: ' 2001 ', classes: [  {   name: ' Three Second class ',   teachers: [    {name: ' Zhang Yi egg ', age:26, Sex: ' Male ', actor: ' Head teacher ',    {name: ' King Chick ', age:23, Sex: ' Female ', actor: ' English Teacher '}   ]  },  {   na Me: ' Star class ',   teachers: [    {name: ' Ouyang Nana ', age:29, Sex: ' Female ', actor: ' Head teacher '},    {name: ' Shen ', age:28, Sex: ' Male ', Actor: ' Sports Teacher '},    {name: ' Yang Mi ', age:111, Sex: ' Female ', actor: ' Art Teacher '}   ]  }]};//general Practice school.classes &&s Chool.classes[0] &&school.classes[0].teachers &&school.classes[0].teachers[0] && school.classes[0].teachers[0].name//Reduce method Const GET = (p, o) = P.reduce ((xs, x) = (xs && xs[x]? Xs[x] : null), O), get ([' classes ', 0, ' teachers ', 0, ' name '], school); Zhang Yi Egg
Fragment 12: Grouping
First through mapCalculates all the key values, and then classifies them according to the built values Fragment 13: Object filtering
Const PICK = (obj, arr) = =
Arr.reduce (ACC, Curr) = (Curr in obj && (Acc[curr] = Obj[curr]), ACC), {});

Pick ({a:1, B: ' 2 ', c:3}, [' A ', ' C ']);

Iterates over the given key value, compares the value of the same key value in the object, and assigns the assigned object to the next initial value through a comma expression

Fragment 14: Delete the value at the specified position in the array

Const REMOVE = (arr, func) = Array.isarray (arr)? Arr.filter (func). Reduce ((ACC, val) = = {   Arr.splice (Arr.indexof (Val), 1);   Return Acc.concat (Val); }, []): [];const arr = [1, 2, 3, 4];remove (arr, n = n% 2 = = 0);

First, the values of the qualifying values in the array are filtered according to the function, and then the value of the qualifying value is removed from the filter reduce original, and the last Arr is converted to [1, 3].

Fragment 15: Promise is executed in sequence

Const RUNPROMISESINSERIES = PS = Ps.reduce (p, next) = P.then (next), Promise.resolve ()), const DELAY = d = new Promise (R = SetTimeout (r, D)), const print = args = new Promise (r = R (args)); Runpromisesinseries ([() = Dela Y (+), () = delay (+), () = print (' Hello ')]);

Episode 16: Sorting

Const-by = (arr, props, orders) = [... Arr].sort ((A, B) and  Props.reduce ((ACC, prop, i) = = {   if (ACC = = = 0) {    const [P1, p2] = orders && orders[i] = = = ' desc '? [B[prop], A[prop]]: [A[prop], b[prop];    ACC = p1 > P2? 1:p1 < P2? -1:0;   }   return acc;  }, 0); const users = [{name: ' Fred ', age:48}, {name: ' Barney ', age:36}, {name: ' Fly ', age:26}];o Rderby (Users, [' Name ', ' age '], [' ASC ', ' desc ']); (Users, [' Name ', ' age ']);

Fragment 17: Select

Const SELECT = (from, selector) = Selector.split ('. '). Reduce ((prev, cur) = prev && prev[cur], from); Const OBJ = {selector: {to: {val: ' Val-to-select '}}};selec T (obj, ' selector.to.val ');

JS Array High-order method reduce classic usage code sharing

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.