我想对数组的元素值求和,它们具有相同的年份。
var newData = [];
var data = new Array(['2013', 0], ['2013', 0],['2016', 15], ['2017', 2], ['2015', 1], ['2013', 0], ['2016', 12], ['2014', 0], ['2017', 3], ['2015', 1], ['2013', 21], ['2013', 2]);
var sum = data.reduce(function (a, b,i) {
if (b[0][i]==b[0][i+1]) {
return newData.push(b[0],a + b[1]);
}
}, 0);
console.log(newData);
//return to:
[
["2013",23],
["2014",0],
["2015",2],
["2016",27],
["2017",5]
]
有可能吗? 谢谢你的帮助
答案 0 :(得分:3)
您可以创建自己的简单且更加理解的自定义逻辑,例如
将JSON对象作为响应。
var newData = [];
var data = new Array(['2013', 0], ['2013', 0],['2016', 15], ['2017', 2], ['2015', 1], ['2013', 0], ['2016', 12], ['2014', 0], ['2017', 3], ['2015', 1], ['2013', 21], ['2013', 2]);
var res = {};
data.forEach((item)=>{
if(Object.keys(res).includes(item[0])){
res[item[0]] += item[1];
} else {
res[item[0]] = item[1];
}
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
将JSON数组作为响应。
var newData = [];
var data = new Array(['2013', 0], ['2013', 0],['2016', 15], ['2017', 2], ['2015', 1], ['2013', 0], ['2016', 12], ['2014', 0], ['2017', 3], ['2015', 1], ['2013', 21], ['2013', 2]);
var res = [];
data.forEach((item)=>{
var found = false;
for(var i=0; i<res.length; i++){
if(res[i][0] === item[0]){
res[i][1] += item[1];
found = true;
break;
}
}
if(!found){
res.push(item);
}
});
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
答案 1 :(得分:3)
您可以将ES6 Map
与reduce
方法一起使用,以按年份汇总值并展开语法...
,以便从地图中获取数组。
var data = new Array(['2013', 0], ['2013', 0], ['2016', 15], ['2017', 2], ['2015', 1], ['2013', 0], ['2016', 12], ['2014', 0], ['2017', 3], ['2015', 1], ['2013', 21], ['2013', 2]);
const result = data.reduce((r, [y, v]) => {
r.set(y, (r.get(y) || 0) + v);
return r;
}, new Map)
console.log([...result]);
&#13;
答案 2 :(得分:1)
如果我理解你的需要,那就试试吧
var sums=data.reduce(function(a,b){
a[b[0]]=(a[b[0]] || 0)+b[1];
},{});
答案 3 :(得分:0)
执行此工作的一种非常快速的方法是使用JS的稀疏数组并选择非空插槽;
var data = [['2013', 0], ['2013', 0],['2016', 15], ['2017', 2], ['2015', 1], ['2013', 0], ['2016', 12], ['2014', 0], ['2017', 3], ['2015', 1], ['2013', 21], ['2013', 2]],
interim = data.reduce((r,e) => (r[+e[0]] && (r[+e[0]][1] += e[1]) || (r[+e[0]] = e), r), []),
result = Object.keys(interim)
.map(k => interim[k]);
console.log(result);
&#13;
.as-console-wrapper {
height : 100%;
max-height : 100% !important
}
&#13;
因此Object.keys(interim)
部分只是以极快的方式过滤掉未定义键的插槽。所以没什么可担心的。看看这个;
var a = [],
b = [];
a[1000000000] = "west";
a[500000000] = "test";
a[0] = "best";
console.time("test");
b = Object.keys(a)
.map(k => a[k]);
console.timeEnd("test");
console.log(b);
&#13;