Table of Contents
Look at w3c syntax first
Common usage
Array summation
Maximum value of array
Advanced usage
Usage in array objects
Find the number of occurrences of letters in a string
Array to array
Array to object
Advanced Usage
Multi-dimensional overlay execution operation
Flat a multi-dimensional array
Object array deduplication
Home Web Front-end JS Tutorial Summary of usage of reduce in javascript (with code)

Summary of usage of reduce in javascript (with code)

Sep 05, 2018 am 11:32 AM
javascript

This article brings you a summary of the usage of reduce in JavaScript (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Recently, I often see others using reduce to process data in projects. It is very awesome and dreamy. It is better to think about it yourself.

Look at w3c syntax first

1

2

3

4

5

6

7

8

array.reduce(function(total, currentValue, currentIndex, arr), initialValue);

/*

  total: 必需。初始值, 或者计算结束后的返回值。

  currentValue: 必需。当前元素。

  currentIndex: 可选。当前元素的索引;                     

  arr: 可选。当前元素所属的数组对象。

  initialValue: 可选。传递给函数的初始值,相当于total的初始值。

*/

Copy after login

Common usage

Array summation

1

2

3

4

5

6

7

8

9

10

11

12

13

const arr = [12, 34, 23];

const sum = arr.reduce((total, num) => total + num);

<!-- 设定初始值求和 -->

const arr = [12, 34, 23];

const sum = arr.reduce((total, num) => total + num, 10);  // 以10为初始值求和

<!-- 对象数组求和 -->

var result = [

  { subject: 'math', score: 88 },

  { subject: 'chinese', score: 95 },

  { subject: 'english', score: 80 }

];

const sum = result.reduce((prev, cur) => prev + cur.score, 0); 

const sum = result.reduce((prev, cur) => prev + cur.score, -10);  // 总分扣除10分

Copy after login

Maximum value of array

1

2

const a = [23,123,342,12];

const max = a.reduce(function(pre,cur,inde,arr){return pre>cur?pre:cur;}); // 342

Copy after login

Advanced usage

Usage in array objects

1

2

3

4

5

6

7

8

9

10

11

12

13

<!-- 比如生成“老大、老二和老三” -->

const objArr = [{name: '老大'}, {name: '老二'}, {name: '老三'}];

const res = objArr.reduce((pre, cur, index, arr) => {

  if (index === 0) {

    return cur.name;

  }

  else if (index === (arr.length - 1)) {

    return pre + '和' + cur.name;

  }

  else {

    return pre + '、' + cur.name;

  }

}, '');

Copy after login

Find the number of occurrences of letters in a string

1

2

const str = 'sfhjasfjgfasjuwqrqadqeiqsajsdaiwqdaklldflas-cmxzmnha';

const res = str.split('').reduce((prev, cur) => {prev[cur] ? prev[cur]++ : prev[cur] = 1; return prev;}, {});

Copy after login

Array to array

1

2

3

<!-- 按照一定的规则转成数组 -->

var arr1 = [2, 3, 4, 5, 6]; // 每个值的平方

var newarr = arr1.reduce((prev, cur) => {prev.push(cur * cur); return prev;}, []);

Copy after login

Array to object

1

2

3

<!-- 按照id 取出stream -->

var streams = [{name: '技术', id: 1}, {name: '设计', id: 2}];

var obj = streams.reduce((prev, cur) => {prev[cur.id] = cur; return prev;}, {});

Copy after login

Advanced Usage

Multi-dimensional overlay execution operation

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

<!-- 各科成绩占比重不一样, 求结果 -->

var result = [

  { subject: 'math', score: 88 },

  { subject: 'chinese', score: 95 },

  { subject: 'english', 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);

 

<!-- 加大难度, 商品对应不同国家汇率不同,求总价格 -->

var prices = [{price: 23}, {price: 45}, {price: 56}];

var rates = {

  us: '6.5',

  eu: '7.5',

};

var initialState = {usTotal:0, euTotal: 0};

var res = prices.reduce((prev1, cur1) => 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);

Copy after login

Flat a multi-dimensional array

1

2

var arr = [[1, 2, 8], [3, 4, 9], [5, 6, 10]];

var res = arr.reduce((x, y) => x.concat(y), []);

Copy after login

Object array deduplication

1

2

3

4

5

6

7

8

9

const hash = {};

  chatlists = chatlists.reduce((obj, next: Object) => {

    const hashId = `${next.topic}_${next.stream_id}`;

    if (!hash[hashId]) {

      hash[`${next.topic}_${next.stream_id}`] = true;

      obj.push(next);

    }

    return obj;

  }, []);

Copy after login

Related recommendations:

Detailed explanation of the use of the reduce() method in JavaScript

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

The above is the detailed content of Summary of usage of reduce in javascript (with code). For more information, please follow other related articles on the PHP Chinese website!

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

Hot Article Tags

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to implement an online speech recognition system using WebSocket and JavaScript

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to implement an online reservation system using WebSocket and JavaScript

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

How to use JavaScript and WebSocket to implement a real-time online ordering system

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecasting system

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

Simple JavaScript Tutorial: How to Get HTTP Status Code

How to get HTTP status code in JavaScript the easy way How to get HTTP status code in JavaScript the easy way Jan 05, 2024 pm 01:37 PM

How to get HTTP status code in JavaScript the easy way

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

How to use insertBefore in javascript

See all articles