reduce

reduce为数组中的每一个元素依次执行callback`函数,不包括数组中被删除或从未被赋值的元素,callback接受四个参数:

  • accumulator 累加器
  • currentValue 当前值
  • currentIndex 当前索引
  • array 数组
arr.reduce(callback[, initialValue])

initialValue可选

作为第一次调用 callback函数时的第一个参数的值。 如果没有提供初始值,则将使用数组中的第一个元素。 在没有初始值的空数组上调用 reduce 将报错。

var result=[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10 );    
运行机制:  
   第一步:  先判断reduce ()方法里面有没有第二个参数    我们这里发现,有第二个参数,为10    
   第二步:  把10 作为  callback函数里的第一个参数  在这里  accumulator 为10     currentValue 为数组中的第一值 0      currentIndex 这里从0  开始  执行完一次callback 函数    得到 10+0  =10     
   第三步    当第二次执行callback 函数的时候,  accumulator  为上次运行的结果 10   currentValue为数组中的第二个值  1     currentIndex  为1      执行完第二次callback 的结果为   为  10+1   =11   
   第四步      第三次执行 callback函数的时候,   accumulator  为上次运行的结果 11   currentValue 为数组中的第三个值  2     currentIndex  为2       执行完第三次callback 的结果   为  11+2   =13
   第五步        第四次执行 callback函数的时候,   accumulator  为上次运行的结果 13  currentValue 为数组中的第四个值  3     currentIndex  为3       执行完第四次callback 的结果   为  13+3   =16
   第六步        第五次执行 callback函数的时候,   accumulator  为上次运行的结果 16  currentValue 为数组中的第五个值  4     currentIndex  为4       执行完第四次callback 的结果   为  16+4  =20
   第七步  :    最后把结果返回为     result      
      

回调函数第一次执行时,accumulatorcurrentValue的取值有两种情况:如果调用reduce()时提供了initialValueaccumulator取值为initialValuecurrentValue取数组中的第一个值;如果没有提供 initialValue,那么accumulator取数组中的第一个值,currentValue取数组中的第二个值。

image-20180929134557313

reduce返回的值将是上次回调调用的值(10)。

第二种情况

如果你打算提供一个初始值作为reduce方法的第二个参数,以下是运行过程及结果:

[0, 1, 2, 3, 4].reduce((accumulator, currentValue, currentIndex, array) => { return accumulator + currentValue; }, 10 );    //20

image-20180929134819078

例子Section

数组里所有值的和
var sum = [0, 1, 2, 3].reduce(function (a, b) {
  return a + b;
}, 0);
// sum is 6

你也可以写成箭头函数的形式:

var total = [ 0, 1, 2, 3 ].reduce(
  ( acc, cur ) => acc + cur,
  0
);

将二维数组转化为一维Section

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(a, b) {
    return a.concat(b);
  },
  []
);
// flattened is [0, 1, 2, 3, 4, 5]

你也可以写成箭头函数的形式:

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
 ( acc, cur ) => acc.concat(cur),
 []
);

计算数组中每个元素出现的次数Section

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

var countedNames = names.reduce(function (allNames, name) { 
  if (name in allNames) {
    allNames[name]++;
  }
  else {
    allNames[name] = 1;
  }
  return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

使用扩展运算符和initialValue绑定包含在对象数组中的数组Section

// friends - an array of objects 
// where object field "books" - list of favorite books 
var friends = [{
  name: 'Anna',
  books: ['Bible', 'Harry Potter'],
  age: 21
}, {
  name: 'Bob',
  books: ['War and peace', 'Romeo and Juliet'],
  age: 26
}, {
  name: 'Alice',
  books: ['The Lord of the Rings', 'The Shining'],
  age: 18
}];

// allbooks - list which will contain all friends' books +  
// additional list contained in initialValue
var allbooks = friends.reduce(function(prev, curr) {
  return [...prev, ...curr.books];
}, ['Alphabet']);

运行机制:1  这里有传参数,['Alphabet'] 当做prev ,  然后通过三个点...解析成 'Alphabet' 
        2   curr 是friends数组中的每一个对象 ,   curr.books  则代表每个对象的每个数组 在这里表现为 3个数组   ['Bible', 'Harry Potter'],   ['War and peace', 'Romeo and Juliet'],  ['The Lord of the Rings', 'The Shining'],  
        3   通过3个点 解析出数组中每个值    结果为  'Alphabet'  'Bible', 'Harry Potter'   然后返回出一个新数组   ['Alphabet'  'Bible', 'Harry Potter']
        4    然后 不断的执行  这个callback  函数         

// allbooks = [
//   'Alphabet', 'Bible', 'Harry Potter', 'War and peace', 
//   'Romeo and Juliet', 'The Lord of the Rings',
//   'The Shining'
// ]

数组去重Section

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
var res=arr.sort()   //返回一个排序后的数组  
 console.log(res)      //[1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 5]
let result = arr.sort().reduce((init, current)=>{
    if(init.length===0 || init[init.length-1]!==current){
        init.push(current);
    }
    return init;
}, []);

 解析步骤   1   先执行  var res=arr.sort()  //返回一个排序后的数组    //[1, 1, 2, 2, 3, 3, 4, 4, 4, 4, 4, 5, 5] 
           2      这里传了一个空数组 []   所以   init  此时是 [ ]    current  是数组的第一个值 为 1    
           3      第一次执行 reduce的回调函数的时候 init.length===0 ,所以进来if  判断  此时 执行 
           init.push(current);1  追加到  init     现在 init  为   [1]
           4     第二次执行 回调函数的时候   curreunt  1   此时 if判断此时进不来  所以不执行  直接跳出
           5      然后每一次执行回调函数 ,每一次进行判断   所以 达到数组去重   

console.log(result); //[1,2,3,4,5]
04-09
### Reduce 的概念与用法 在编程和数据处理领域,`Reduce` 是一种重要的函数式编程工具,通常用于聚合操作。它通过反复应用某个二元函数(即接受两个参数并返回单一结果的函数),将一组输入值逐步缩减为单个输出值。 #### MapReduce 中的 Reduce 阶段 在分布式计算框架 `MapReduce` 中,`Reduce` 被定义为接收来自多个映射器(mappers)的结果,并对其进行汇总的过程[^1]。具体来说,在日志分析场景下,`map` 函数会生成键值对 `<url, 1>` 表示每次访问某 URL 的记录;随后,`reduce` 函数负责统计相同 URL 的总次数,最终输出形如 `<url, total count>` 的结果[^2]。 以下是 Python 实现的一个简单例子来展示 reduce 如何工作: ```python from functools import reduce # 假设我们有一系列数值列表 numbers = [1, 2, 3, 4] # 使用 lambda 定义求和逻辑作为 reduce 的回调函数 sum_result = reduce(lambda x, y: x + y, numbers) print(sum_result) # 输出应为 10 ``` 此代码片段展示了如何利用内置库中的 `functools.reduce()` 方法完成累加运算。这里的关键在于传入了一个匿名函数 (`lambda`) 来指定每一步的操作规则——即将当前累积值与下一个待处理项相加。 #### 循环对比 Reduce 尽管可以通过显式的循环结构实现类似的聚集功能,但采用高阶函数形式往往更加简洁明了[^3]。例如下面两种方式均能达成相同的计数目的: 基于传统迭代版本: ```python count = 0 for num in numbers: count += num print(count) ``` 而借助于 reduce 则显得更为紧凑高效: ```python total_count = reduce((lambda acc, val: acc + val), numbers, 0) print(total_count) ``` 上述两段程序虽然语法不同,但实际上执行的是完全一致的任务:遍历整个数组并将其中各元素逐一加入到初始状态之中去形成最后的整体数量度量标准。 ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值