I am trying to think of the best way of looping through this array of data objects and if the wineRegion name appears more than once, I want the output array to hold this value once with the totalPrice value incremented to the value of all the matching objects totalPrice.
Here is my data array:
const data = [
{
wineName: 'Château Pape-Clément',
wineRegion: 'Bordeaux (Red)',
unitSize: '12x75cl',
wineVintage: 2010,
qty: 1,
totalPrice: 1650,
},
{
wineName: 'Château Beauséjour Duffau-Lagarrosse',
wineRegion: 'Bordeaux (Red)',
unitSize: '6x75cl',
wineVintage: 2010,
qty: 1,
totalPrice: 1400,
},
{
wineName: 'Vosne-Romanée, Berthaut',
wineRegion: 'Burgundy (Red)',
unitSize: '12x75cl',
wineVintage: 2017,
qty: 1,
totalPrice: 510,
},
{
wineName: 'Mazis-Chambertin, Faiveley',
wineRegion: 'Burgundy (Red)',
unitSize: '6x75cl',
wineVintage: 2018,
qty: 1,
totalPrice: 790,
},
{
wineName: 'Gevrey-Chambertin Les Champeaux, O. Bernstein',
wineRegion: 'Burgundy (Red)',
unitSize: '3x75cl',
wineVintage: 2019,
qty: 1,
totalPrice: 675,
},
{
wineName: 'Latricières-Chambertin, J. M. Fourrier',
wineRegion: 'Burgundy (Red)',
unitSize: '6x75cl',
wineVintage: 2017,
qty: 1,
totalPrice: 1050,
},
{
wineName: 'Corton Rognet, Taupenot-Merme',
wineRegion: 'Burgundy (Red)',
unitSize: '6x75cl',
wineVintage: 2019,
qty: 1,
totalPrice: 600,
},
{
wineName: 'Corton-Charlemagne, Ponsot',
wineRegion: 'Burgundy (White)',
unitSize: '6x75cl',
wineVintage: 2012,
qty: 1,
totalPrice: 980,
},
{
wineName: 'Bollinger Grand Année',
wineRegion: 'Champagne ',
unitSize: '6x75cl',
wineVintage: 2008,
qty: 1,
totalPrice: 675,
},
{
wineName: "L'Astre, David Léclapart",
wineRegion: 'Champagne ',
unitSize: '6x75cl',
wineVintage: 2013,
qty: 1,
totalPrice: 540,
},
{
wineName: 'Brunello di Montalcino Madonna delle Grazie, Marroneto',
wineRegion: 'Italy ',
unitSize: '6x75cl',
wineVintage: 2012,
qty: 1,
totalPrice: 945,
},
];
So, for example, the output array will hold the data in a similar format as above but the multiple objects that have wineRegion: 'Bordeaux (Red)' will only appear once in the output array and the totalPrice will be the sum of all the totalPrice values. So loop through the array and if a duplicate value exists for regionName, increment the totalPrice.
I have tried to use reduce but couldn't solve this myself.