I am learning .reduce(), and come up with using .reduce to reduce the pairs array to a single object with the key-value totals.
There is a line I don't understand.
Here is the code:
function GroupTotals(strArr) {
// Create an empty object to store the key-value totals
var totals = {};
// Split each string in strArr by ":" and parse the value as an integer
// Then, create an array of [key, value] pairs for each string
var pairs = strArr.map(s => s.split(/:/)).map(s => [s[0], parseInt(s[1])]);
// Reduce the pairs array to a single object with the key-value totals
totals = pairs.reduce((acc, s) => (acc[s[0]] = (acc[s[0]] || 0) + s[1], acc), {});
// Create an array of keys from the totals object, sort them alphabetically,
// filter out any keys with a total value of 0, and map the remaining keys
// to "key:total" strings
var output = Object.keys(totals).sort().filter(k => totals[k] !== 0).map(k => `${k}:${totals[k]}`);
// Join the output array with commas to form the final output string
return output.join(',');
}
I don't understand why in the line, that acc at the end of the line ,acc),{}) mean "return acc".
totals = pairs.reduce((acc, s) => (acc[s[0]] = (acc[s[0]] || 0) + s[1], acc), {});
Correct me if I am wrong, I think it is the same as
function sumPairs(acc, s) {
acc[s[0]] = (acc[s[0]] || 0) + s[1];
return acc;
}
const totals = pairs.reduce(sumPairs, {});
Please explain why ,acc mean "return acc". I tried to look up in mdn syntax, but couldn't figure it out.
Hope it make sense and thank you in advance. This is the first time I ask a question in stack flow.