如果其他列的值匹配,则获取列的总和 [英] Get sum of columns if values of other columns match
本文介绍了如果其他列的值匹配,则获取列的总和的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有这个矩阵算法问题:
I have this matrix algorithm problem:
输入:
const testObj = [
['Anna', 10, 'Monday'],
['Anna', 15, 'Wednesday'],
['Beatrice', 8, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 4, 'Wednesday'],
['Beatrice', 5, 'Monday'],
['Beatrice', 16, 'Monday']
]
输出:
let resultObj = [
['Anna', 10, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 19, 'Wednesday'],
['Beatrice', 27, 'Monday']
]
基本上,如果是同一个人(col0)和同一天(col2),则获取col1的总和,然后合并.
Basically, if it's the same person (col0) and the same day (col2), get the sum of col1, and merge.
我正在使用javascript解决此问题,但是任何语言的建议都可以.我已经做到了:
I'm solving this with javascript but any suggestion in any language will do. I've done this:
const solveThis = async(obj) => {
for (let i = 0; i < obj.length; i += 1) {
if (obj[i + 1] && (obj[i][0] === obj[j][0]) && (obj[i][2] === obj[j][2])) {
let sum = obj[i][1] + obj[j][1],
newRow = new Array(obj[i + 1][0], sum, obj[i + 1][2])
obj.push(newRow)
let indexi = obj.indexOf(obj[i]),
indexj = obj.indexOf(obj[j])
obj.splice(indexi, 1)
obj.splice(indexj, 1
}
}
return obj
}
solveThis(testObj).then(result => console.log(result))
它不起作用.
推荐答案
首先使用 name | day
键创建一个对象,然后获取值.
First make a object with name|day
keys and then get values.
const data = [['Anna', 10, 'Monday'],['Anna', 15, 'Wednesday'],['Beatrice', 8, 'Monday'],['Beatrice', 11, 'Wednesday'],['Anna', 4, 'Wednesday'],['Beatrice', 5, 'Monday'],['Beatrice', 16, 'Monday']]
const result = data.reduce((r, [name, v, day]) => {
const key = `${name}|${day}`;
if(!r[key]) r[key] = [name, v, day];
else r[key][1] += v;
return r;
}, {})
console.log(Object.values(result))
这篇关于如果其他列的值匹配,则获取列的总和的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文