reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
array.reduce(function(prev, cur, index, arr), init)
带初始值
var arr = [1,2,3,4] var sum = arr.reduce((pre, item) => { return pre + item }, 10) console.log(sum) // 20
不带初始值
var arr = [1,2,3,4] var sum = arr.reduce((pre, item) => { return pre + item },) console.log(sum) // 10
var arr = [1,2,3,3,2,1,4] arr.reduce((acc, cur) => { if (!(acc.includes(cur))) { acc.push(cur) } return acc }, []) // [1, 2, 3, 4]
var arr = [1, 2, 3, 4]; arr.reduce((prev, cur) => { return Math.max(prev,cur); }); //4
var arr = [[1,2], [3,4], [5,6]] arr.reduce((acc, cur) => { return acc.concat(cur) }, []) // [1,2,3,4,5,6]
var arr = [ {subject: 'Math', score: 90}, {subject: 'Chinese', score: 90}, {subject: 'English', score: 100} ] arr.reduce((pre, cur) => { return cur.score + pre }, 0) //280
var arr = [1, 2,3,3,2,1,2,1] arr.reduce((acc, cur) => { if (!(cur in acc)) { acc[cur] = 1 } else { acc[cur] += 1 } return acc }, {}) //{1: 3, 2: 3, 3: 2}
var arr = [ {subject: 'Math', score: 90}, {subject: 'Chinese', score: 90}, {subject: 'English', score: 100}, {subject: 'Math', score: 80}, {subject: 'Chinese', score: 95} ]; arr.reduce((acc, cur) => { if (!acc[cur.type]) { acc[cur.type] = []; } acc[cur.type].push(cur) return acc }, {})
var arr = [1, 2, 3, 4] Array.prototype.reduceMap = function(callback) { return this.reduce((acc, cur, index, array) => { const item = callback(cur, index, array) acc.push(item) return acc }, []) } arr.reduceMap((item, index) => { return item + index }) // [1, 3, 5, 7]
var arr = [1, 2, 3, 4] Array.prototype.reduceForEach = function(callback) { this.reduce((acc, cur, index, array) => { callback(cur, index, array) }, []) } arr.reduceForEach((item, index, array) => { console.log(item, index) }) // 1234 // 0123
var arr = [1, 2, 3, 4] Array.prototype.reduceFilter = function (callback) { return this.reduce((acc, cur, index, array) => { if (callback(cur, index, array)) { acc.push(cur) } return acc }, []) } arr.reduceFilter(item => item % 2 == 0) // 过滤出偶数项。 // [2, 4]
var arr = [1, 2, 3, 4] var obj = [{ a: 1 }, { a: 2 }, { a: 3 }, { a: 4 }] Array.prototype.reduceFind = function (callback) { return this.reduce((acc, cur, index, array) => { if (callback(cur, index, array)) { if (acc instanceof Array && acc.length == 0) { acc = cur } } if ((index == array.length - 1) && acc instanceof Array && acc.length == 0) { acc = undefined } return acc }, []) } arr.reduceFind(item => item % 2 == 0) // 2 obj.reduceFind(item => item.a % 2 == 0) // {a: 2} obj.reduceFind(item => item.a % 9 == 0) // undefined