关于JavaScript中的reduce()方法

更新日期: 2020-03-12阅读: 1.5k标签: reduce

一、什么是 reduce() ?

reduce() 方法对数组中的每个元素执行一个升序执行的 reducer 函数,并将结果汇总为单个返回值

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// 输出: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// 输出: 15

 

二、数组中 reduce 方法的参数

1、第一个参数:reducer 函数

其中,reducer 函数又有四个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)

2、第二个参数(可选):initialValue

代表传递给函数的初始值

// 不传第二个参数的情况
var numbers = [1, 2, 3, 4]

function myFunction(item) {
    let result = numbers.reduce(function (total, currentValue, currentIndex, arr) {
        console.log(total, currentValue, currentIndex, arr)
        return total + currentValue
    })
    return result
}

myFunction(numbers)

输出:


可以看到如果不传第二个参数 initialValue,则函数的第一次执行会将数组中的第一个元素作为 total 参数返回。一共执行3次

下面是传递第二个参数的情况:

// 不传第二个参数的情况
var numbers = [1, 2, 3, 4]

function myFunction(item) {
    let result = numbers.reduce(function (total, currentValue, currentIndex, arr) {
        console.log(total, currentValue, currentIndex, arr)
        return total + currentValue
    }, 10)
    return result
}

myFunction(numbers)

输出:


如果传了第二个参数 initialValue,那么第一次执行的时候 total 的值就是传递的参数值,然后再依次遍历数组中的元素。执行4次

总结:如果不传第二参数 initialValue,那么相当于函数从数组第二个值开始,并且将第一个值最为第一次执行的返回值,如果传了第二个参数 initialValue,那么函数从数组的第一个值开始,并且将参数 initialValue 作为函数第一次执行的返回值

 

三、应用场景

1、数组里所有值的和

var sum = [0, 1, 2, 3].reduce(function (accumulator, currentValue) {
  return accumulator + currentValue;
}, 0);
// 和为 6

2、累加对象数组里的值

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(function (accumulator, currentValue) {
    return accumulator + currentValue.x;
},initialValue)

console.log(sum) // logs 6

3、将二维数组转化为一维

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

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

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 }

5、数组去重

var myArray = ['a', 'b', 'a', 'b', 'c', 'e', 'e', 'c', 'd', 'd', 'd', 'd'];
var myOrderedArray = myArray.reduce(function (accumulator, currentValue) {
  if (accumulator.indexOf(currentValue) === -1) {
    accumulator.push(currentValue);
  }
  return accumulator
}, [])

console.log(myOrderedArray);
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
let result = arr.sort().reduce((init, current) => {
    if(init.length === 0 || init[init.length-1] !== current) {
        init.push(current);
    }
    return init;
}, []);
console.log(result); //[1,2,3,4,5]

 

链接: https://www.fly63.com/article/detial/8213

Reducer的深入理解

要理解 reducer 的第一点也是最重要的一点是它永远返回一个值,这个值可以是数字、字符串、数组或对象,但它始终只能是一个。reducer 对于很多场景都很适用,但是它们对于将一种逻辑应用到一组值中并最终得到一个单一结果的情况特别适用

reduce方法应用技巧

reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。注意: reduce() 对于空数组是不会执行回调函数的。

Js中的reduce,fold和unfold

说说reduce吧, 很喜欢这个函数,节省了不少代码量,而且有一些声明式的雏形了,一些常见的工具函数,flatten,deepCopy,mergeDeep等用reduce实现的很优雅简洁。reduce也称为fold,本质上就是一个折叠数组的过程

js中reduce的神奇用法

最近经常在项目中经常看到别人用reduce处理数据,很是牛掰,很梦幻, 不如自己琢磨琢磨。

JavaScript中的reduce()的5个用例

在本文中,我们讨论了数组 reduce() 方法。首先介绍 reduce() 方法,然后,使用一个简单的示例讨论其行为。最后,通过示例讨论了 reduce() 方法最常见的五个用例

代码写得好,Reduce 方法少不了

reduce 接受两个参数,回调函数和初识值,初始值是可选的。回调函数接受4个参数:积累值、当前值、当前下标、当前数组。如果 reduce的参数只有一个,那么积累值一开始是数组中第一个值

js中数组reduce的使用原来这么简单

没有提供初始值,索引是从1开始的。提供了初始值索引是从0开始的。没有提供初始值循环次数等于数组长度-1。 提供了初始值循环次数等于数组的长度;没有提供初始值第一次cur是索引为1的那个值。提供了初始值cur是索引为0的那个值

面试官直呼内行!如何实现一个比较完美的reduce函数?

reduce() 方法对数组中的每个元素按序执行一个由用户提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。

js 使用reduce方法合并两个对象数组,有则替换,无则新增

有两个对象数组A和B,现在需要将两个数组中的对象合并,有则替换,无则新增,数组如下所示;我们分析下A和B数组,A和B中都存在name=李四的对象

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!