归并方法
const arr = [1, 2, 3, 4, 5];/*** reduce/reduceRight* v1: 归并函数* v1: 归并值* v2: 当前项* v3: 当前项索引* v4: 数组本身* v2: 归并起点*/const red = arr.reduce(function (x, y, i, arr) {console.log("i :>> ", i);return x * y;});console.log(red);const redR = arr.reduceRight((x, y, i, arr) => x * y);console.log(redR);
案例: 将班级中同学的名字全部提取出来
const classes = [{class: "一班",students: [{name: "小王",age: 18,},{name: "小李",age: 21,},],},{class: "二班",students: [{name: "小孙",age: 16,},{name: "小赵",age: 28,},],},];const studentsName = classes.reduce(function (pre, cur, index, array) {let stus = pre.students.reduce(function (pre, cur, index, array) {return pre.name.concat(cur.name);});return stus.concat(cur.students.reduce(function (pre, cur, index, array) {return pre.name.concat(cur.name);}));});console.log(studentsName);
案例: 统计
const fruits = ["苹果", "橘子", "梨", "苹果"];const fruitsCount = fruits.reduce(function (pre, next) {pre[next] = pre[next] + 1 || 1;return pre;}, {});console.log(fruitsCount);
案例: 去重
const fruitsOnly = fruits.reduce(function (pre, cur, index, array) {if (pre.indexOf(cur) == -1) {pre.push(cur);}return pre;}, []);console.log(fruitsOnly);
