我有这个矩阵算法问题:
输入:
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的总和,并合并。
我正在用 javascript 解决这个问题,但任何语言的任何建议都可以。我已经这样做了:
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
键创建一个对象,然后获取值。
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))
关于javascript - 如果其他列的值匹配,则获取列的总和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50419051/