# 关于数组对应下标计算问题 Array

200 次浏览
``````let list= [["现金",12,1,8],["算款",5,0,0],["回购",1,0,0],["到期",10,0,20],["存款",0,10,0],["其它",0,50,0]]

//每个数组里面对应下标累积相加，最后希望得到下面结果，请问该用什么方法去实现呢
{"0":"合计","1":28,"2":61,"3":28}``````
http_404 186
2018-12-07 提问
3 个回答

``````let list = [['现金', 12, 1, 8], ['算款', 5, 0, 0], ['回购', 1, 0, 0], ['到期', 10, 0, 20], ['存款', 0, 10, 0], ['其它', 0, 50, 0]];

let result = list.reduce((res, arr) => {
arr.forEach((num, index) => {
if (index) {
res[index] = (res[index] || 0) + num;
}
});
return res;
}, {'0': '合计'});

console.log(result);``````

``````let list= [
["现金",12,1,8],
["算款",5,0,0],
["回购",1,0,0],
["到期",10,0,20],
["存款",0,10,0],
["其它",0,50,0]
];

const handleData = (data) => {
// 获取最大下标
let maxIndex = data.map(item => item.length).sort((a,b)=> b-a)[0];

// 定义结果（数组）
let resArr = new Array(maxIndex).fill(0);

// 处理数据
data.forEach( item => {
item.forEach( (v, i) => {
resArr[i] += (v || 0)
})
});

// res转对象格式
let res = {};
resArr.forEach( (v, i)=> {
res[i] = i == 0 ? '合计' : v
});

return res;
}

console.log( handleData(list));``````

``````var list= [["现金",12,1,8],["算款",5,0,0],["回购",1,0,0],["到期",10,0,20],["存款",0,10,0],["其它",0,50,0]];
function test2(list){
var obj = {'0':'合计'};
for(var x=0;x<list.length;x++){
for(var i=0;i<list[x].length;i++)
i>0&&(obj[i]=obj[i]==null?list[x][i]:obj[i]+list[x][i]);
}
return obj;
}
test2(list);``````