H5W3

# es6 reduce()使用案例

reduce()方法对数组中的每一个元素执行一个reducer函数(由你提供)，从而得到一个单一的输出值。

`reduce()` 方法将一个数组中的所有元素还原成一个单一的输出值，输出值可以是数字、对象或字符串。 `reduce()` 方法有两个参数，第一个是回调函数，第二个是初始值

## 回调函数

• Accumulator（累加器）——累加器累加回调函数的返回值。
• Current Value（当前值）——处理数组的当前元素。
• Current Index（当前索引）——处理数组当前元素的索引。
• Source Array（源数组）

`Current Index ``Source Array `是可选的。

## 初始值

``arr.reduce(callback(accumulator, currentValue[,index[,array]])[, initialValue])``

``````const numbersArr = [67, 90, 100, 37, 60];
const total = numbersArr.reduce(function(accumulator, currentValue){
console.log("accumulator is " + accumulator + " current value is " + currentValue);
return accumulator + currentValue;
}, 0);
console.log("total : "+ total);``````

``````accumulator is 0 current value is 67
accumulator is 67 current value is 90
accumulator is 157 current value is 100
accumulator is 257 current value is 37
accumulator is 294 current value is 60
total : 354``````

## JavaScript reduce用例

### 1.对数组的所有值求和

``````const studentResult = [67, 90, 100, 37, 60];
const total = studentResult.reduce((accumulator, currentValue) => accumulator +currentValue, 0);
console.log(total); // 354``````

### 2.对象数组中的数值之和

``````const studentResult = [
{ subject: '数学', marks: 78 },
{ subject: '物理', marks: 80 },
{ subject: '化学', marks: 93 }
];
const total = studentResult.reduce((accumulator, currentValue) => accumulator + currentValue.marks, 0);
console.log(total); // 251``````

### 3.展平数组

“展平数组”是指将多维数组转换为一维。在下面的代码中，`twoDArr` 2维数组被转换为 `oneDArr` 一维数组。此处，第一个 `[1,2]` 数组分配给累加器 `accumulator`，然后 `twoDArr` 数组的其余每个元素都连接到累加器。

``````const twoDArr = [ [1,2], [3,4], [5,6], [7,8] , [9,10] ];
const oneDArr = twoDArr.reduce((accumulator, currentValue) => accumulator.concat(currentValue));
console.log(oneDArr);
// [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]``````

### 4.按属性分组对象

``````const result = [
{subject: '物理', marks: 41},
{subject: '化学', marks: 59},
{subject: '高等数学', marks: 36},
{subject: '应用数学', marks: 90},
{subject: '英语', marks: 64},
];
let initialValue = {
pass: [],
fail: []
}
const groupedResult = result.reduce((accumulator, current) => {
(current.marks >= 50) ? accumulator.pass.push(current) : accumulator.fail.push(current);
return accumulator;
}, initialValue);
console.log(groupedResult);``````

``````{
pass: [
{ subject: ‘化学’, marks: 59 },
{ subject: ‘应用数学’, marks: 90 },
{ subject: ‘英语’, marks: 64 }
],
fail: [
{ subject: ‘物理’, marks: 41 },
{ subject: ‘高等数学’, marks: 36 }
]
}``````

### 5.删除数组中的重复项

``````const duplicatedsArr = [1, 5, 6, 5, 7, 1, 6, 8, 9, 7];
const removeDuplicatedArr = duplicatedsArr.reduce((accumulator, currentValue) => {
if(!accumulator.includes(currentValue)){
accumulator.push(currentValue);
}
return accumulator;
}, []);
console.log(removeDuplicatedArr);
// [ 1, 5, 6, 7, 8, 9 ]``````