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))
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; }
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;
};
添加回答
举报