第七色在线视频,2021少妇久久久久久久久久,亚洲欧洲精品成人久久av18,亚洲国产精品特色大片观看完整版,孙宇晨将参加特朗普的晚宴

為了賬號(hào)安全,請(qǐng)及時(shí)綁定郵箱和手機(jī)立即綁定
已解決430363個(gè)問題,去搜搜看,總會(huì)有你想問的

怎么實(shí)現(xiàn)數(shù)組內(nèi)對(duì)象code值相同的情況下poll值進(jìn)行累加

怎么實(shí)現(xiàn)數(shù)組內(nèi)對(duì)象code值相同的情況下poll值進(jìn)行累加

胡子哥哥 2019-03-15 14:15:07
var arr = [    {"code": "a", "poll": 7},    {"code": "b", "poll": 2},    {"code": "c", "poll": 18},    {"code": "a", "poll": 5},    {"code": "c", "poll": 12},    {"code": "a", "poll": 1}];var arr2 = [{"code": "a", "poll": 13},{"code": "b", "poll": 2},{"code": "c", "poll": 30}];如何實(shí)現(xiàn)arr → 到arr1 的轉(zhuǎn)變,且code值 不僅僅為 a b c 也可能為 adsdsd dsdsd a223 任意值 如何實(shí)現(xiàn) 類似轉(zhuǎn)變
查看完整描述

3 回答

?
躍然一笑

TA貢獻(xiàn)1826條經(jīng)驗(yàn) 獲得超6個(gè)贊

給你來一個(gè)不考慮性能的


var arr = [

  {"code": "a", "poll": 7},

  {"code": "b", "poll": 2},

  {"code": "c", "poll": 18},

  {"code": "a", "poll": 5},

  {"code": "c", "poll": 12},

  {"code": "a", "poll": 1}

];


let arr1 = arr.sort((pre, next) => pre.code > next.code).reduce((pre, v) => {

  let lastIndex = pre.length - 1;

  if (lastIndex >= 0 && pre[lastIndex].code === v.code) {

    pre[lastIndex].poll += v.poll;

  } else {

    pre.push(Object.assign({}, v));

  }

  return pre;

}, []);

console.log(arr1);

再來個(gè)一次遍歷的,以空間換時(shí)間。


function pollAdd(arr) {

  let res = [];

  let tmp = {};


  arr.forEach((v) => {

    if (!tmp.hasOwnProperty(v.code)) {

      tmp[v.code] = res.length;

      return res.push(Object.assign({}, v));

    }

    res[tmp[v.code]].poll += v.poll;

  });


  return res;

}


查看完整回答
反對(duì) 回復(fù) 2019-04-25
?
慕絲7291255

TA貢獻(xiàn)1859條經(jīng)驗(yàn) 獲得超6個(gè)贊

你這是js吧


    var arr = [

        {"code": "a", "poll": 7},

        {"code": "b", "poll": 2},

        {"code": "c", "poll": 18},

        {"code": "a", "poll": 5},

        {"code": "c", "poll": 12},

        {"code": "a", "poll": 1}

    ];

    var newArr = [];

    for (i in arr) {

        if(typeof(newArr[arr[i].code]) == 'undefined'){

            newArr[arr[i].code] = 0;

        }

        newArr[arr[i].code] += arr[i].poll;

    }


查看完整回答
反對(duì) 回復(fù) 2019-04-25
  • 3 回答
  • 0 關(guān)注
  • 455 瀏覽

添加回答

舉報(bào)

0/150
提交
取消
微信客服

購課補(bǔ)貼
聯(lián)系客服咨詢優(yōu)惠詳情

幫助反饋 APP下載

慕課網(wǎng)APP
您的移動(dòng)學(xué)習(xí)伙伴

公眾號(hào)

掃描二維碼
關(guān)注慕課網(wǎng)微信公眾號(hào)