问题
I have this matrix algorithm problem:
Input:
const testObj = [
['Anna', 10, 'Monday'],
['Anna', 15, 'Wednesday'],
['Beatrice', 8, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 4, 'Wednesday'],
['Beatrice', 5, 'Monday'],
['Beatrice', 16, 'Monday']
]
Output:
let resultObj = [
['Anna', 10, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 19, 'Wednesday'],
['Beatrice', 27, 'Monday']
]
Basically, if it's the same person (col0) and the same day (col2), get the sum of col1, and merge.
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))
and it doesn't work.
回答1:
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))
回答2:
You can use the array .reduce
method to create the new array. For each item, use .find
to see if there is an existing item with matching name and day. If so, add the values, otherwise put the item into the new array.
Example:
const testObj = [
['Anna', 10, 'Monday'],
['Anna', 15, 'Wednesday'],
['Beatrice', 8, 'Monday'],
['Beatrice', 11, 'Wednesday'],
['Anna', 4, 'Wednesday'],
['Beatrice', 5, 'Monday'],
['Beatrice', 16, 'Monday']
];
function merge(arr) {
return arr.reduce((merged, item) => {
const existing = merged.find(o => o[0] === item[0] && o[2] === item[2]);
existing
? existing[1] += item[1]
: merged.push(item);
return merged;
}, []);
}
console.log(merge(testObj));
来源:https://stackoverflow.com/questions/50419051/get-sum-of-columns-if-values-of-other-columns-match