I am using vanilla js for this helper function inside of a react app / typescript. Json data is fetched this holds every letter of the alphabet which is assigned a value and a key. These are layed out into a grid of tiles. When a user selects a tile, this is added to gameData array in React which is used for a list. If a user clicks onto the same tile this is merged so instead of multiple list elements with same values they are merged with quantity + quantity and value + value
The structure is as such
const apiData = [
{key: 'A', value: 50, quantity: 1, color: '#3498db', ...etc},
{key: 'B', value: 40, quantity: 1, color: '#e67e22', ...etc},
...
]
const gameData = [
{key: 'A', value: 200, quantity: 4, color: '#3498db', ...etc},
{key: 'E', value: 10, color: '#fa0', ...etc},
]
export function groupBy(array: GameData[]) {
const group: GameData[] = Object.values(
array.reduce((acc: any, { value, quantity, ...r }) => {
const key = Object.entries(r).join("-");
acc[key] = acc[key] || { ...r, quantity: 0, value: 0 };
return ((acc[key].value += value), (acc[key].quantity += 1)), acc;
}, {})
);
return group;
}
The reducer works and merges properly but I just feel like there must be a better way to do this. Any ideas?
for..ofinstead of reduce, but using the same basic principle.