Array.reduce() 数组内置方法
reduce的意思是“把...数量、程度或大小上变小”。 对于Array.reduce()来说,就是把数组元素通过特定的逻辑(callback)转成更小的数组或某一特定的类型。
正因如此,它非常的灵活,功能也非常的强大,是其他数组内置方法所不能比拟的
在使用reduce()方法的时候,对于非确定元素个数的数组,始终加个initVal会更加的保险
const numbers = [1,2,3] const summation = numbers.reduce( (accumulator, curVal) => accumulator + curVal, 0 ) console.log(summation ) //6
实战使用-数组转数字
const salary = 30000; const consumption = [ {cost: 6000, type:'a'}, {cost: 2000, type:'b'}, {cost: 3000, type:'c'}, {cost: 4000, type:'d'}, ] const balance = consumption.reduce((accumulator,curVal) => accumulator - curVal.cost,salary) console.log('balance:',balance); // balance: 150000
实战使用-对象转数组
const ageGroup = [18,21,1,1,41,14,4,13,14,5,10] const uniqueAgeGroup = ageGroup.reduce((accumulator,currentValue) => { if(!accumulator.includes(currentValue)){ accumulator.push(currentValue); } return accumulator },[]) console.log('uniqueAgeGroup:',uniqueAgeGroup); // uniqueAgeGroup: (9) [18, 21, 1, 41, 14, 4, 13, 5, 10]
实战使用-数组转对象
const people = [ {name: 'John',age: 23}, {name: 'Orage',age: 18}, {name: 'Pink',age: 25}, {name: 'Redux',age: 56}, {name: 'Kerwin',age: 25}, {name: 'Ww',age: 18}, {name: 'Fincus',age: 56}, ] const groupBy = (objectArray,property) => { return objectArray.reduce((accumulator,currentObject) => { const key = currentObject[property]; if(!accumulator[key]){ accumulator[key] = [] } accumulator[key].push(currentObject); return accumulator },{}) } const groupPeople = groupBy(people,'age'); console.log('groupPeople:',groupPeople); //{
18: (2) [{name: 'Orage', age: 18}, {name: 'Ww', age: 18}]
23:[{name: 'John', age: 23}]
25: (2) [{name: 'Pink', age: 25}, {name: 'Kerwin', age: 25}]
56: (2) [{name: 'Redux', age: 56}, {name: 'Fincus', age: 56}]
}