用reduce求和
const sum = [1,2,3,4,5,6].reduce((v,t)=>{
return v+t;
//第一次v=0,t=1
//第二次v= 0+1,t=2
//第三次v=1+2,t=3......
},0)//reduce传入两个值,第一个是个函数,第二个是初始值
map处理字符串然后用reduce
const joined = 'this-is-an-example';
joined
.split('-')
.map( word => {//用map将每个单词的第一个字符变成大写
const [head,...others] = word
console.log(head,others);
return head.toUpperCase() + others.reduce((x,y) => x+y,'')
})
.reduce( (s,word)=>{
console.log('word=='+word);
return s+' '+word;
})
console.log(joined);
map/reduce处理sql
本质上所有数据处理过程(sql过程)都是map/reduce,所以可以使用map/reduce完成大量操作。而高阶函数让我们可以最大化复用这个计算过程
//所有数据处理都是sql,用map/reduce完成一些sql操作
//假设数据库中有一张成绩单,如下
let students = {
{id:1,name:'lucy',score:99,class:'a'},
{id:2,name:'lily',score:88,class:'b'}
}
let selected = students.map( student => {
return {name:student.name}//最终只会输出name这一字段的值
})
console.log(selected);
//比如筛选所有分数大于80的学生 即select name from students where score>80
let selected2 = students.reduce( (list,student) => {
if(student.score > 80){
list = [...list,student]
}
return list;
},[])
console.log(selected2);
/*===================================================*/
//对上述条件筛选的另一思路 map/reduce与高阶函数
//先把函数提取出来,此时并没有用到高阶函数
let selectScoreLargerThan80 = (list,student) => {
if(student.score > 80){
list = [...list,student];
}
return list;
}
//const selected_2 = students.reduce(selectScoreLargerThan80,[])
//定义一个高阶函数filter,用于生成筛选条件
const filter = (prediction) => {
return (list,item) => {
if(prediction(item)){
list = [...list,item];
}
}
}
//使用filter增加筛选条件
const selectScoreLargerThan80_2 = filter(item => item.score > 60)
const selected_2_2 = students.reduce(selectScoreLargerThan80,[])
/*=========================================*/
//按照分数排序(倒序)
//插入排序 select * from students order by score desc
const sorted = students.reduce( (list,student) => {
let i = 0;
for(;i<list.length;i++){//这里是插入的过程,排序条件是可变的,所以可以把这部分封装到一个高阶函数
if(list[i].score < student.score) break;
}
return [...list.slice(0,i),student,...list.slice(i,list.length)];//插入排序
},[])
/*========================================*/
//按照班级进行排序(groupby),然后求最大分数,插入排序
// select max(score) from students group by class
//将学生按照class分组
const grouped = students.reduce( (groups,student) => {
if(!groups[student.class]){
groups[student.class] = {key:student.class,values:[]}
}
groups[student.class].values.push(student)
return groups
},{})
//提取为数组
const arrGroups = Object.values(grouped);
//计算每个分组的最大值
const final = arrGroups.map(group => {
return {
class:group.key,
max:group.values.reduce( (a,b) => {
return b.score > a ? b.score : a;
},0)
}
})
console.log(final);
/*===========================*/
//使用原生的filter与find
const selected = students.filter(student => student.score > 60)
const student = students.find(student => student.id === 5)
const sorted = students.sort((student1,student2) => student1.score < student2.score )
整理自魏蒙老师视频