用reduce求和sql
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 )
整理自魏蒙老師視頻this