Get Sum Of Columns If Values Of Other Columns Match
I have this matrix algorithm problem: Input: const testObj = [ ['Anna', 10, 'Monday'], ['Anna', 15, 'Wednesday'], ['Beatrice', 8, 'Monday'], ['Beatrice', 11, 'Wednesday'], ['A
Solution 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))
Solution 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']
];
functionmerge(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));
Post a Comment for "Get Sum Of Columns If Values Of Other Columns Match"