猿问

给定一个数组,如 [[el1,el2],[el11,el22],[el111,el222]]

当我有这样的数组时


var test = [['11 may 2018',0],['11 may 2018',1],['12 may 2018',5],['13 may 2018',0],['14 may 2018',0],['15 may 2018',3],['15 may 2018',7],['16 may 2018',30]];

我希望它最终看起来像这样


var test2 = [['11 may 2018',1],['12 may 2018',5],['13 may 2018',0],['14 may 2018',0],['15 may 2018',10],['16 may 2018',30]]

我不知道该怎么做。


我做了类似的事情:


    var test = [['11 may 2018',0],['11 may 2018',1],['12 may 2018',5],['13 may 2018',0],['14 may 2018',0],['15 may 2018',3],['15 may 2018',7],['16 may 2018',30]];

var test2 = [['11 may 2018',1],['12 may 2018',5],['13 may 2018',0],['14 may 2018',0],['15 may 2018',10],['16 may 2018',30]]


var testLength = test.length;


for (let i = 0; i< testLength; i++){

    if(i != testLength -1){

        if(test[i][0] == test[i+1][0]){

            test[i][1] += test[i+1][1];

        }

    }


}

console.log(test)

哪个返回


    [

  [ '11 may 2018', 1 ],

  [ '11 may 2018', 1 ],

  [ '12 may 2018', 5 ],

  [ '13 may 2018', 0 ],

  [ '14 may 2018', 0 ],

  [ '15 may 2018', 10 ],

  [ '15 may 2018', 7 ],

  [ '16 may 2018', 30 ]

]

我不知道如何在不弄乱索引的情况下删除重复数组的第二个实例


哔哔one
浏览 90回答 3
3回答

扬帆大鱼

只需跟踪键入日期的对象中的日期,并在迭代列表时递增。最后Object.entries,对象将是您想要的:var test = [['11 may 2018',0],['11 may 2018',1],['12 may 2018',5],['13 may 2018',0],['14 may 2018',0],['15 may 2018',3],['15 may 2018',7],['16 may 2018',30]];let counts =&nbsp; test.reduce((sums, [key, count]) => {&nbsp; &nbsp; sums[key] = (sums[key] || 0) + count&nbsp; &nbsp; return sums}, {})console.log(Object.entries(counts))

PIPIONE

您可以使用一个对象来对相同的键进行分组,并从该对象中获取值作为结果。var array = [['11 may 2018', 0], ['11 may 2018', 1], ['12 may 2018', 5], ['13 may 2018', 0], ['14 may 2018', 0], ['15 may 2018', 3], ['15 may 2018', 7], ['16 may 2018', 30]],&nbsp; &nbsp; result = Object.values(array.reduce((r, [key, value]) => {&nbsp; &nbsp; &nbsp; &nbsp; r[key] = r[key] || [key, 0];&nbsp; &nbsp; &nbsp; &nbsp; r[key][1] += value;&nbsp; &nbsp; &nbsp; &nbsp; return r;&nbsp; &nbsp; }, {}));console.log(result);.as-console-wrapper { max-height: 100% !important; top: 0; }

潇潇雨雨

您实际上需要一个Map结构来解决此类问题。你可以这样做:const buildMap = arr => {&nbsp; &nbsp; const map = {};&nbsp; &nbsp; arr.forEach(element => {&nbsp; &nbsp; &nbsp; &nbsp; const [key, value] = element;&nbsp; &nbsp; &nbsp; &nbsp; if (map[key]) map[key] += value;&nbsp; &nbsp; &nbsp; &nbsp; else {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; map[key] = value;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });&nbsp; &nbsp; return map;};
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答