• Array reduce() 如何计算元素内数值总合,计算总合


    Array reduce() 如何计算元素内数值总合,计算总合

    一、需求

    有时候我们需要计算一个数组中所有元素的总合,这个数组可能是组 Number 类型,也可能是 Object 类型,像这样:

    const tempArray = [2,3,4,6,456,89,24]
    // 或
    const wantedThings = [
    	{owned: true,  sold: false, priceSold: 0,    date: '2022-02-17', priceOrigin: 207,       price: 207,       title: "Timebox-EVO",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-02-12', priceOrigin: 3200,      price: 3200,      title: "驾校 C1",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-02-12', priceOrigin: 849,       price: 849,       title: "小米乳胶床垫",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-12-16', priceOrigin: 500,       price: 500,       title: "鼠标Master3",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-12-06', priceOrigin: 245,       price: 245,       title: "Apple AirTag",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-11-05', priceOrigin: 750,       price: 470,       title: "维迈通 v9s",},
        {owned: true,  sold: false, priceSold: 0,    date: '2021-08-28', priceOrigin: 2600,      price: 2600,      title: "头盔AGV K5s",},
    ]
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11

    比如我要知道所有 Object.price 的总合是多少,可以通过 Array.forEach 来遍历,但还有更好的方法吗?
    答案是肯定的,这个需求是 Array 经常会遇到的,所以它有一个专用的方法来实现这个功能: Array.reduce()

    二、Array.reduce() 语法

    MDN 官方说明: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce

    ? 表示可选

    reduce(function (accumulator, currentValue, ?currentIndex, ?array) { /* … */ }, ?initValue)
    
    // 翻译过来就是
    reduce(function (上一个结果的值, 当前元素值, ?当前index, ?原array数组) { 这里写你要运行的操作:你可操作的变量有(上一个结果,当前值) }, ?临时汇总变量的初始值)
    
    • 1
    • 2
    • 3
    • 4

    Array.reduce() 的字面意思就是依次递减,正如它的字面意思,它的作用就是依次遍历数组中的每个元素,最终返回一个结果。
    至于这个遍历过程中的操作是加还是减,完全取决于你。

    比如你要计算一个数组的所有元素的和

    let temp = [1,2,3,4,5,6,7,8,9,10];
    let initValue = 0;
    let sumOfArray = temp.reduce((tempSum, currentItemValue) => tempSum + currentItemValue, initValue)
    
    // 完整的写法
    let sumOfArray =
        temp.reduce(
            function (tempSum, currentItemValue) {
                return tempSum + currentItemValue
            }, initValue)
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10

    它的结果是:
    在这里插入图片描述

    三、实际使用

    比如我要知道最初那个数组的所有 price 的和:

    const wantedThings = [
        {owned: true,  sold: false, priceSold: 0,    date: '2022-02-17', priceOrigin: 207,       price: 207,       title: "Timebox-EVO",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-02-12', priceOrigin: 3200,      price: 3200,      title: "驾校 C1",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-02-12', priceOrigin: 849,       price: 849,       title: "小米乳胶床垫",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-12-16', priceOrigin: 500,       price: 500,       title: "鼠标Master3",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-12-06', priceOrigin: 245,       price: 245,       title: "Apple AirTag",},
        {owned: true,  sold: false, priceSold: 0,    date: '2022-11-05', priceOrigin: 750,       price: 470,       title: "维迈通 v9s",},
        {owned: true,  sold: false, priceSold: 0,    date: '2021-08-28', priceOrigin: 2600,      price: 2600,      title: "头盔AGV K5s",},
    ]
    
    let totalCostOwn = wantedThings
                        .filter(item => item.owned)
                        .reduce((sum, currentValue) => sum + currentValue.price, 0)
    
    let totalCost = wantedThings
                        .reduce((sum, currentValue) => sum + currentValue.price, 0)
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    是不是比用 .forEachfor(;;) 要优雅

    在这里插入图片描述

  • 相关阅读:
    Mycat中间件分配数据库
    Spring-Web(一) RestTemplate使用与源码浅析
    金仓数据库 KingbaseES 插件参考手册 I
    推送服务接入指导(HarmonyOS篇)
    Uniapp 生命周期
    pytorch 初始化
    初刷leetcode题目(5)——数据结构与算法
    【第五篇】商城系统-商品属性管理
    C++ 17 filesystem
    亚马逊云科技面向 macOS 的 Amazon 云服务器 EC2 M1 Mac 实例
  • 原文地址:https://blog.csdn.net/KimBing/article/details/128060449