```
之前就用到过一些 Reduce 的一些巧妙用法,比如生成一个新对象今天看到一片不错的文章,就把文章一些精华记下,当作一个笔记吧。
```
文章引自 [25个你不得不知道的数组reduce高级用法](https://juejin.cn/post/6844904063729926152)
##### reduce 介绍
reduce的精华所在是将累计器逐个作用于数组成员上,把上一次输出的值作为下一次输入的值。下面举个简单的栗子,看看reduce的计算结果。
```js
const arr = [3, 5, 1, 4, 2];
const a = arr.reduce((t, v) => t + v);
const b = arr.reduce((t, v) => t + v, 0);
```
- 定义:对数组中的每个元素执行一个自定义的累计器,将其结果汇总为单个返回值
- 形式:array.reduce((t, v, i, a) => {}, initValue)
- callback:回调函数(必选)
- initValue:初始值(可选)
- total(t):累计器完成计算的返回值(必选)
- value(v):当前元素(必选)
- array(a):当前元素所属的数组对象(可选)
---
对空数组调用reduce()和reduceRight()是不会执行其回调函数的,可认为reduce()对空数组无效
---
###### 累加累乘
```js
function Accumulation(...vals) {
return vals.reduce((t, v) => t + v, 0);
}
function Multiplication(...vals) {
return vals.reduce((t, v) => t * v, 1);
}
```
###### 权重求和
```
const scores = [
{ score: 90, subject: "chinese", weight: 0.5 },
{ score: 95, subject: "math", weight: 0.3 },
{ score: 85, subject: "english", weight: 0.2 }
];
const result = scores.reduce((t, v) => t + v.score * v.weight, 0);
```
###### 代替map和filter
```
const arr = [0, 1, 2, 3];
// map
const a = arr.map(v => v * 2);
const b = arr.reduce((t, v) => [...t, v * 2], []);
// filter
const c = arr.filter(v => v > 1);
const d = arr.reduce((t, v) => v > 1 ? [...t, v] : t, []);
// 代替map和filter:[4, 6]
const e = arr.map(v => v * 2).filter(v => v > 2);
const f = arr.reduce((t, v) => v * 2 > 2 ? [...t, v * 2] : t, []);
```