I have this code snippet I'm using to group by a key field.
It's using the reduce function and I understand the code except the part where the result or accumulator of the function is being edited.
If I were to write this code, I'd have an external empty array to push my results to and not edit the object in the function.
The code works as intended but I was wondering if this is common practice.
function groupBy(array, key) {
return array.reduce((result, currentItem) => {
const groupByKey = currentItem[key];
// Create a new array for the key if it doesn't exist in the result
if (!result[groupByKey]) {
result[groupByKey] = [];
}
// Push the current item to the array of the corresponding key
result[groupByKey].push(currentItem);
return result;
}, {});
}
// Example usage:
const data = [
{ id: 1, category: 'A' },
{ id: 2, category: 'B' },
{ id: 3, category: 'A' },
{ id: 4, category: 'C' },
{ id: 5, category: 'B' },
];
I believe it's a good practice to try keeping your functions pure indeed, especially with these functional patterns, although in this case, it isn't much of an issue, given the initial value of the accumulator is
{}, an object literal that has been built specifically to be passed to thatreduce.It would be an issue if the accumulator were used beforehand/afterhand, for example:
In a nutshell, your current impl is acceptable IMO, but I would have written it without mutating
resulteither personally.