reduce() 方法接收一个函数作为累加器,reduce 为数组中的每一个元素依次执行回调函数,不包括数组中被删除或从未被赋值的元素,
接收四个参数:
初始值(上一次回调的返回值)
当前元素值
当前索引,
原数组
初始值 initialValue 可以是 Object 类型
语法 array.reduce(callback, [ initialValue])
callback: 函数中包含 四个参数
previousValue (上一次调用回调返回的值,或者是提供的初始值(initialValue))
currentValue 数值中当前被处理的元素
index 当前元素在 数值中的索引
array 调用的数组
应用
const arr = [1, 2, 3, 4, 5]
const sum = arr.reduce((pre, item) => {
return pre + item
}, 0)
console.log(sum) // 15
以上回调被调用5次,每次的参数详见下表
![](https://img.haomeiwen.com/i15638448/75bc0947b6f9e2c5.png)
利用reduce来计算一个字符串中每个字母出现次数
var str = 'yutianyang';
var obj = str.split('').reduce((previous, current) => {
previous[current]? previous[current] ++ : previous[current] = 1;
return previous;
}, {})
console.log(obj);
/**
*
* {
a: 2
g: 1
i: 1
n: 2
t: 1
u: 1
y: 2
}
* */
递归利用reduce处理tree树形
var data = [
{
id: 1,
name: "办公管理",
pid: 0,
children: [{
id: 2,
name: "请假申请",
pid: 1,
children: [
{ id: 4, name: "请假记录", pid: 2 },
],
},
{ id: 3, name: "出差申请", pid: 1 },
]
},
{
id: 5,
name: "系统设置",
pid: 0,
children: [{
id: 6,
name: "权限管理",
pid: 5,
children: [
{ id: 7, name: "用户角色", pid: 6 },
{ id: 8, name: "菜单设置", pid: 6 },
]
}, ]
},
];
let arr = data.reduce(function(pre,item){
const callee = arguments.callee //将运行函数赋值给一个变量备用
pre.push(item)
if(item.children && item.children.length > 0) item.children.reduce(callee,pre); //判断当前参数中是否存在children,有则递归处理
return pre;
},[]);
console.log(arr)
arr= arr.map((item) => {
item.children = []
return item
})
console.log(arr)
二维数组转为一维数组
var array = [[1, 2], [3, 4], [5, 6]].reduce(( acc, cur ) => {
return acc.concat(cur)
}, []);
console.log(array) // [ 0, 1, 3, 4, 5, 6 ]
数组去重
var arr1 = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4]
var arr2 = [];
arr1.sort().reduce((previous, current) => {
if (previous.length === 0 || previous[previous.length -1] !== current){
arr2.push(current)
}
return arr2
}, []);
console.log(arr2) //[1, 2, 3, 4, 5]
网友评论