为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

哔哔one 2022-05-26 10:47:00
当我有这样的数组时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 ]]我不知道如何在不弄乱索引的情况下删除重复数组的第二个实例
查看完整描述

3 回答

?
扬帆大鱼

TA贡献1799条经验 获得超9个赞

只需跟踪键入日期的对象中的日期,并在迭代列表时递增。最后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 =  test.reduce((sums, [key, count]) => {

    sums[key] = (sums[key] || 0) + count

    return sums

}, {})


console.log(Object.entries(counts))


查看完整回答
反对 回复 2022-05-26
?
PIPIONE

TA贡献1829条经验 获得超9个赞

您可以使用一个对象来对相同的键进行分组,并从该对象中获取值作为结果。


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]],

    result = Object.values(array.reduce((r, [key, value]) => {

        r[key] = r[key] || [key, 0];

        r[key][1] += value;

        return r;

    }, {}));


console.log(result);

.as-console-wrapper { max-height: 100% !important; top: 0; }


查看完整回答
反对 回复 2022-05-26
?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

您实际上需要一个Map结构来解决此类问题。你可以这样做:


const buildMap = arr => {

    const map = {};

    arr.forEach(element => {

        const [key, value] = element;

        if (map[key]) map[key] += value;

        else {

            map[key] = value;

        }

    });

    return map;

};


查看完整回答
反对 回复 2022-05-26
  • 3 回答
  • 0 关注
  • 89 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信