JavaScript高级函数reduce应用

377 阅读2分钟

写作出发点:

作为一个nodejs开发人员,每天需要处理很多业务数据,不乏对数组和数组对象有很多操作,而我们又不想个别情况下使用效率极低的for...for嵌套,又想提高执行效率,故而研究JavaScript高阶函数的使用之reduce(),及其附加旁枝的一些方法(map, filter等)处理。

概念:

reduce()是JavaScript中Array对象原型上的方法,接收一个函数作为累加器(accumulator),对每个元素(从左到右)依次应用该函数,将前一个结果和当前元素进行计算得到新的结果,并返回最终的累加结果。

reduce()函数有两个参数: 1、函数(accumlator, currentValue, currentIndex, array):必需。用于计算每一次迭代产生的结果,每一次迭代计算得到的结果会作为下一次迭代的第一个参数传入。 2、初始值(initialvalue):可选。用于指定每个迭代的第一个参数accumlator的初始值。如果没有指定该参数,则将使用数组中的第一个元素作为初始值。

reduce()函数使用场景:

  1. 数组求和
// for循环求和
const arr = [1,2,3,4,5]
let sum = 0
for (let i = 0; i < arr.length; i++) {
   sum += arr[i]
} // 1,2,3,4,5分别累计加: 15

// reduce()求和, 0表示accumulator的初始值, currentValue表示每次遍历过程中的1,2,3,4,5
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue, 0); console.log(sum); // 15
  1. 数组去重
// 场景1:(简单数组处理)
// 新创建数组,并遍历数组,将每一个参数进行判断是否不包含在新数组中,是:不添加,否:添加
const arr = [1, 2, 3, 4, 5, 4, 5, 6, 2, 3]
let unique = []
for (const item of arr) {
   if (!unique.includes(item)) unique.push(item)
} // unique=[ 1, 2, 3, 4, 5, 6 ]

// 获取使用map
arr.map((item) => {
   if (!unique.includes(item)) unique.push(item)
})

// 使用filter
const unique = arr.filter((item, index, self) => {
   return self.indexOf(item) === index
}) // 输出unique

// new Set()
const unique = [...new Set(arr)]

// 场景2:(数组对象处理)
const data = [{
   'goodsId': '1',
   'quota': 12,
   'skuId': '1'
},
{
   'goodsId': '2',
   'quota': 12,
   'skuId': '2'
},
{
   'goodsId': '1',
   'quota': 12,
   'skuId': '3'
}]
// 使用map处理
let obj = {}
arr.map((item) => {
   obj[item.name] = item
})
// obj: 
/*{
  '1': { goodsId: '1', quota: 12, skuId: '1' },
  '2': { goodsId: '2', quota: 12, skuId: '2' }
}*/
let newArr = Object.values(obj) /*[
  { goodsId: '1', quota: 12, skuId: '1' },
  { goodsId: '2', quota: 12, skuId: '2' }
]
*/

// 使用reduce
let result = arr.reduce((accumulator, currentValue) => {
   if (!accumulator.some(item => item.name === currentValue.name)) {
      accumulator.push(currentValue)
   }
   return accumulator
}, []) // some()方法判断是否存在相同的元素
  1. 对象数组分组
const data = [
   { name: 'Amy', age: 18, gender: 'female' },
   { name: 'Bob', age: 20, gender: 'male' },
   { name: 'Cindy', age: 18, gender: 'female' },
   { name: 'Dave', age: 22, gender: 'male' },
   { name: 'Emily', age: 20, gender: 'female' }
]
const groups = data.reduce((accumulator, currentValue) => {
   accumulator[currentValue.age] = (accumulator[currentValue.age] || []).push(currentValue)
   return accumulator
}, {})

未完待补充......