【问题标题】:How to get total of values in array of javascript objects如何获取javascript对象数组中的总值
【发布时间】:2018-09-28 11:23:52
【问题描述】:

我有以下数组:

[
{genderAge: "Male 25-39", count: 13029, weightedCount: 18475.6824262314, matchingSegment: 2},
{genderAge: "Female 55+", count: 35639, weightedCount: 32294.5926147014, matchingSegment: 8},
{genderAge: "Female 25-39", count: 23285, weightedCount: 20645.0599977815, matchingSegment: 6},
{genderAge: "Female 18-24", count: 7745, weightedCount: 8497.30029399032, matchingSegment: 5},
{genderAge: "Male 55+", count: 38018, weightedCount: 28589.2793936886, matchingSegment: 4},
{genderAge: "Male 18-24", count: 4038, weightedCount: 8122.65161312996, matchingSegment: 1},
{genderAge: "Female 40-54", count: 23051, weightedCount: 22834.3167597392, matchingSegment: 7},
{genderAge: "Male 40-54", count: 17278, weightedCount: 19681.8852663563, matchingSegment: 3}
]

我想将此对象数组转换为一个数组,其中包含两个对象,其中包含男性和女性的汇总数据(计数、加权计数和匹配段)。有没有使用 Lodash 和/或 ES6 实现此目的的捷径?

更新:很抱歉我提供了错误的数据。

【问题讨论】:

    标签: javascript arrays object ecmascript-6 lodash


    【解决方案1】:
    function sumFor(pattern, data) {
      return data
        .filter(item => item.text.match(pattern))
        .reduce((accu, item) => accu + item.total, 0);
    }
    sumFor(/^Male/, data); // 125480
    sumFor(/^Female/, data); // 154916
    

    【讨论】:

    • 我喜欢 :) 有了 sn-p 就完美了
    【解决方案2】:

    你可以使用reduce方法

    var list = [
    {genderAge: "Male 25-39", count: 13029, weightedCount: 18475.6824262314, matchingSegment: 2},
    {genderAge: "Female 55+", count: 35639, weightedCount: 32294.5926147014, matchingSegment: 8},
    {genderAge: "Female 25-39", count: 23285, weightedCount: 20645.0599977815, matchingSegment: 6},
    {genderAge: "Female 18-24", count: 7745, weightedCount: 8497.30029399032, matchingSegment: 5},
    {genderAge: "Male 55+", count: 38018, weightedCount: 28589.2793936886, matchingSegment: 4},
    {genderAge: "Male 18-24", count: 4038, weightedCount: 8122.65161312996, matchingSegment: 1},
    {genderAge: "Female 40-54", count: 23051, weightedCount: 22834.3167597392, matchingSegment: 7},
    {genderAge: "Male 40-54", count: 17278, weightedCount: 19681.8852663563, matchingSegment: 3}
    ]
    
    list.reduce(function(a, b) {
         if(/^Male/.test(b['genderAge'])) {
            a['male']['pop'] += b['count'];
            a['male']['matchingSegment'] += b['matchingSegment'];
            a['male']['weightedCount'] += b['weightedCount'];
        } else if(/^Female/.test(b['genderAge'])){
            a['female']['pop'] += b['count'];
            a['female']['matchingSegment'] += b['matchingSegment'];
            a['female']['weightedCount'] += b['weightedCount'];
        }
         return a;
    }, {'male':{'pop':0, 'matchingSegment':0, 'weightedCount':0}, 'female':{'pop':0, 'matchingSegment':0, 'weightedCount':0}});
    

    【讨论】:

      【解决方案3】:

      您可以按想要的值分组并获得total 的总和。

      var data = array = [{ text: "Male 18-24 (12886)", value: "test_1", total: 12886 }, { text: "Male 25-39 (27913)", value: "test_2", total: 27913 }, { text: "Male 40-54 (29793)", value: "test__3", total: 29793 }, { text: "Male 55+ (54888)", value: "test__4", total: 54888 }, { text: "Female 18-24 (19354)", value: "test_5", total: 19354 }, { text: "Female 25-39 (43972)", value: "test_6", total: 43972 }, { text: "Female 40-54 (39327)", value: "test_7", total: 39327 }, { text: "Female 55+ (52263)", value: "test_8", total: 52263 }],
          result = _(data)
              .groupBy(o => o.text.match(/^\S+/)[0])
              .map((array, group) => ({ group, sum: _.sumBy(array, 'total') }))
              .value();
      
          console.log(result);
      <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>

      【讨论】:

        【解决方案4】:

        const { Sum, mreduceMap, compose, propOr, ifElse, constant } = crocks
        
        const data = [
          {text: "Male 18-24 (12886)", value: "test_1", total: 12886},
          {text: "Male 25-39 (27913)", value: "test_2", total: 27913},
          {text: "Male 40-54 (29793)", value: "test__3", total: 29793},
          {text: "Male 55+ (54888)", value: "test__4", total: 54888},
          {text: "Female 18-24 (19354)", value: "test_5", total: 19354},
          {text: "Female 25-39 (43972)", value: "test_6", total: 43972},
          {text: "Female 40-54 (39327)", value: "test_7", total: 39327},
          {text: "Female 55+ (52263)", value: "test_8", total: 52263}
        ]
        
        const startsWith = x => str =>
          typeof str === 'string' &&
          str.startsWith(x)
        
        const isSex = sex =>
          compose(startsWith(sex), propOr('', 'text'))
        
        const totalFor = sex =>
          ifElse(isSex(sex), propOr(0, 'total'), constant(0))
        
        const sumSex = sex =>
          mreduceMap(Sum, totalFor(sex))
        
        const sumMales = sumSex('Male')
        const sumFemales = sumSex('Female')
        
        const males = sumMales(data)
        const females = sumFemales(data)
        
        console.log({males, females})
        <script src="https://unpkg.com/crocks@0.10.1/dist/crocks.min.js"></script>

        使用crocks 库,您可以使用功能强大的方法来解决问题。

        【讨论】:

          【解决方案5】:

          ES6

          .reduce((acc,e)=>{
            if (/^Male/.test(e.text)){
             acc[0].total+=e.total
            }
            if (/^Female/.test(e.text)){
             acc[1].total+=e.total
            }
            return acc
          },[{total:0},{total:0}])
          

          【讨论】:

          • 一般来说,在回答时你应该提供一些关于代码如何工作的细节的解释性文字。
          【解决方案6】:

          您可以简单地用两个objects 初始化array,第一个用于Male,第二个用于Female

          let result = [{text: "Male", total:0}, {text: "Female", total:0}];
          

          然后使用forEach 循环在您的第一个array 上填充相关数据。

          array.forEach(function(a){
             if(a.genderAge.indexOf("Male")>-1){
                result[0].total += a.count;
             }else if(a.genderAge.indexOf("Female")>-1){
                result[1].total += a.count;
             }
          });
          

          演示:

          var array = [
          {genderAge: "Male 25-39", count: 13029, weightedCount: 18475.6824262314, matchingSegment: 2},
          {genderAge: "Female 55+", count: 35639, weightedCount: 32294.5926147014, matchingSegment: 8},
          {genderAge: "Female 25-39", count: 23285, weightedCount: 20645.0599977815, matchingSegment: 6},
          {genderAge: "Female 18-24", count: 7745, weightedCount: 8497.30029399032, matchingSegment: 5},
          {genderAge: "Male 55+", count: 38018, weightedCount: 28589.2793936886, matchingSegment: 4},
          {genderAge: "Male 18-24", count: 4038, weightedCount: 8122.65161312996, matchingSegment: 1},
          {genderAge: "Female 40-54", count: 23051, weightedCount: 22834.3167597392, matchingSegment: 7},
          {genderAge: "Male 40-54", count: 17278, weightedCount: 19681.8852663563, matchingSegment: 3}
          ];
          
          let result = [{text: "Male", total:0}, {text: "Female", total:0}];
          
          array.forEach(function(a){
             if(a.genderAge.indexOf("Male")>-1){
                result[0].total += a.count;
             }else if(a.genderAge.indexOf("Female")>-1){
                result[1].total += a.count;
             }
          });
          
          console.log(result);

          【讨论】:

            【解决方案7】:

            这是另一种简单的 lodash 方法,它使用 _.groupBy 并且只执行一个循环:

            var data = [ {genderAge: "Male 25-39", count: 13029, weightedCount: 18475.6824262314, matchingSegment: 2}, {genderAge: "Female 55+", count: 35639, weightedCount: 32294.5926147014, matchingSegment: 8}, {genderAge: "Female 25-39", count: 23285, weightedCount: 20645.0599977815, matchingSegment: 6}, {genderAge: "Female 18-24", count: 7745, weightedCount: 8497.30029399032, matchingSegment: 5}, {genderAge: "Male 55+", count: 38018, weightedCount: 28589.2793936886, matchingSegment: 4}, {genderAge: "Male 18-24", count: 4038, weightedCount: 8122.65161312996, matchingSegment: 1}, {genderAge: "Female 40-54", count: 23051, weightedCount: 22834.3167597392, matchingSegment: 7}, {genderAge: "Male 40-54", count: 17278, weightedCount: 19681.8852663563, matchingSegment: 3} ]
            
            const getGenderTotals = data => {
               let Males = 0, Females = 0
               _.groupBy(data, (r => {/^Male/.test(r.genderAge) ? Males += r.count : Females += r.count}))
               return { Males, Females }
            }
            
            console.log(getGenderTotals(data))
            <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.10/lodash.min.js"></script>

            由于我们可以访问该值并且我们在 _.groupBy 上下文中,您还可以轻松地在 groupBy iteratee 函数中返回 MaleFemale 以获取实际的组等。

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 2022-01-02
              • 1970-01-01
              • 2019-10-02
              • 1970-01-01
              • 1970-01-01
              • 2021-09-02
              • 2019-01-03
              • 2021-09-13
              相关资源
              最近更新 更多