1. js数组中reduce的各参数介绍
let arrList = [ 1,2,2,3,4 ]
/**
* 回调
* prev 上一个数据记录
* cur 当前元素
* arr 当前数组
*/
let callback = (prev,cur,index,arr) => { .... }
/**
* 参数一 回调
* 参数二 初始化数据 (如果有那么在开始时prev就会使用它,没有prev就会选用数组第一个元素,会少做一次循环)
*/
arrList.reduce(callback,init)
例子:
let arrList = [1,2,2,3,4]
let callback = (prev,cur,index,arr) => {
console.log(prev,'_',cur,"_",index,"_",arr);
return prev + cur
}
let sum = arrList.reduce(callback,0)
console.log('__',sum)
/**
* 结果
* 0 '_' 1 '_' 0 '_' [1, 2, 2, 3, 4]
* 1 '_' 2 '_' 1 '_' [1, 2, 2, 3, 4]
* 3 '_' 2 '_' 2 '_' [1, 2, 2, 3, 4]
* 5 '_' 3 '_' 3 '_' [1, 2, 2, 3, 4]
* 8 '_' 4 '_' 4 '_' [1, 2, 2, 3, 4]
* __ 12
*/
let sum2 = arrList.reduce(callback)
console.log('__',sum2)
/**
* 结果
* 1 '_' 2 '_' 1 '_' [1, 2, 2, 3, 4]
* 3 '_' 2 '_' 2 '_' [1, 2, 2, 3, 4]
* 5 '_' 3 '_' 3 '_' [1, 2, 2, 3, 4]
* 8 '_' 4 '_' 4 '_' [1, 2, 2, 3, 4]
* __ 12
*/
2. 各种用处
2.1 数组累加求和
代码在上面介绍里
2.2 数组去重
let arrList = [1,2,2,3,3,4,5];
let list = arrList.reduce((prev,cur)=>{
if(prev.indexOf(cur)===-1) {
prev.push(cur)
}
return prev
},[])
console.log(list) // [1, 2, 3, 4, 5]
let arrList = [
{id:'111',name:'aaaa'},
{id:'222',name:'bbbb'},
{id:'111',name:'cccc'},
{id:'333',name:'dddd'},
{id:'444',name:'eeee'},
{id:'333',name:'ffff'},
];
let obj = {}
let list = arrList.reduce((prev,cur)=>{
if(!obj[cur.id]) {
obj[cur.id] = true;
prev.push(cur)
}
return prev
},[]);
console.log(list)
/** [
* {id: '111', name: 'aaaa'},
* {id: '222', name: 'bbbb'},
* {id: '333', name: 'dddd'},
* {id: '444', name: 'eeee'}
* ]
*/
2.3 统计字符出现次数
const strCount = (arr) => {
return arr.reduce((prev, cur) => {
if (cur in prev) {
prev[cur]+=1;
} else {
prev[cur] = 1;
}
return prev
}, {})
}
const ret = strCount(['a', 'a', 'b', 'c', 'd'])
console.log(ret)
// {a: 2, b: 1, c: 1, d: 1}
2.4 过滤数据
// 过滤age大于等于13的对象
let arrList = [
{id:'111',name:'aaaa',age:10},
{id:'222',name:'bbbb',age:12},
{id:'111',name:'cccc',age:13},
{id:'333',name:'dddd',age:14},
{id:'444',name:'eeee',age:12},
{id:'333',name:'ffff',age:15},
];
let list = arrList.reduce((prev,cur)=>{
if(cur.age<13) {
prev.push(cur)
}
return prev
},[]);
console.log(list)
/**
* [
* {id: '111', name: 'aaaa', age: 10}
* {id: '222', name: 'bbbb', age: 12}
* {id: '444', name: 'eeee', age: 12}
* ]
*/