Summary of usage of reduce in JavaScript (with code)

Source: Internet
Author: User
Tags prev
This article brings you the content is about the use of reduce in JavaScript summary (with code), there is a certain reference value, the need for friends can refer to, I hope to help you.

Recently often in the project to see others using reduce processing data, is a cow break, very dreamy, rather than their own pondering.

First look at the grammar

Array.reduce (function (total, CurrentValue, Currentindex, arr), initialvalue);/*  total: Required. The initial value, or the return value after the calculation has ended.  CurrentValue: Required. The current element.  currentindex: Optional. The index of the current element;                       arr: Optional. The array object to which the current element belongs.  initialvalue: Optional. The initial value passed to the function, equivalent to the initial value of total. */

Common usage

Array summation

Const ARR = [23];const sum = arr.reduce (total, num)-+ total + num);<!--Set initial value summation-->const arr = [12, 34, 23];const sum = arr.reduce (total, num)-= total + num,  Sum <!--An array of initial values with 10-->var result = [  {subject: ' Math ', score:88},  {subject: ' Chinese ', score:95},  {subject: ' 中文版 ', score:80}];const sum = Result.reduce ((prev, cur) = prev + cur.score, 0); Const SUM = result.reduce ((prev, cur) = prev + Cur.score, -10);  Total deduction 10 points

Array Maximum Value

Const A = [23,123,342,12];const max = A.reduce (function (Pre,cur,inde,arr) {return pre>cur?pre:cur;}); 342

Advanced usage

Usage in array objects

<!--such as "Boss, Dick and old three"-->const Objarr = [{name: ' Boss '}, {name: ' Dick '}, {name: ' Old three '}];const res = objarr.reduce (PRE, cur , index, arr) = = {  if (index = = 0) {    return cur.name;  }  else if (index = = = (arr.length-1)) {    return pre + ' and ' + Cur.name;  }  else {    return pre + ', ' + Cur.name;  }}, ');

To find the number of occurrences of a letter in a string

Const STR = ' Sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha '; const RES = Str.split ("). Reduce ((prev, cur) + = { Prev[cur]? prev[cur]++: prev[cur] = 1; return prev;}, {});

Array to array

<!--according to certain rules to the group-->var arr1 = [2, 3, 4, 5, 6]; The square var of each value Newarr = Arr1.reduce ((prev, cur) + = {Prev.push (cur * cur); return prev;}, []);

Array to Object

<!--remove stream by id-->var streams = [{name: ' Technology ', id:1}, {name: ' design ', id:2}];var obj = Streams.reduce ((prev, cur) = = {Prev[cur.id] = cur; return prev;}, {});

Advanced usage

Multi-dimensional overlay execution action

<!--the results of different subjects are different,-->var result = [{subject: ' Math ', score:88}, {subject: ' Chinese ', score:95}, {Subje CT: ' 中文版 ', score:80}];var dis = {math:0.5, chinese:0.3, English:0.2};var res = result.reduce (prev, cur ) = Dis[cur.subject] * cur.score + prev, 0);<!--to increase the difficulty, the goods corresponding to different countries exchange rates, the total price-->var prices = [{price:23}, {Price:4 5}, {Price:56}];var rates = {us: ' 6.5 ', EU: ' 7.5 ',};var initialstate = {ustotal:0, eutotal:0};var res = Prices.reduce  (Prev1, Cur1) and Object.keys (rates). Reduce ((Prev2, cur2) = {Console.log (prev1, Cur1, Prev2, CUR2);  prev1[' ${cur2}total '] + = Cur1.price * RATES[CUR2]; return PREV1;}, {}), initialstate), var managereducers = function () {return function (state, item) {return Object.keys        (rates). Reduce ((nextstate, key) = {state[' ${key}total '] + = Item.price * Rates[key];      return state;  }, {}); }};var res1= Prices.reduce (Managereducers (), initialstate);

Flat a multidimensional array

var arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];var res = Arr.reduce ((x, y) + x.concat (y), []);

Object array de-weight

Const HASH = {};  Chatlists = Chatlists.reduce ((obj, next:object) and {    const Hashid = ' ${next.topic}_${next.stream_id} ';    if (!hash[hashid]) {      hash[' ${next.topic}_${next.stream_id} '] = true;      Obj.push (next);    }    return obj;  }, []);
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: [email protected] 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.