'How can i use reduce or any other array method, to count and sum up specific properties?
I try to learn more about the array methods and also working with objects. I come up with this dummy example that simulate an incoming data.
const data = [
{
id: 1,
name: 'Company 1',
sales: 100,
status: 'win',
brand: 'dell',
year: 2020,
},
{
id: 2,
name: 'Company 2',
sales: 300,
status: 'lost',
brand: 'dell',
year: 2020,
},
{
id: 3,
name: 'Company 3',
sales: 600,
status: 'pending',
brand: 'acer',
year: 2021,
},
{
id: 4,
name: 'Company 3',
sales: 800,
status: 'pending',
brand: 'lenovo',
year: 2021,
},
{
id: 5,
name: 'Company 4',
sales: 400,
status: 'lost',
brand: 'apple',
year: 2020,
},
{
id: 6,
name: 'Company 1',
sales: 1000,
status: 'win',
brand: 'apple',
year: 2020,
},
]
I would like to manipulate the information so i could come up with a new array like this:
const projects = [
{
period: 2020,
uniqueCompanies: 3,
totalProjects: 4,
totalSales: 1800,
winStatus: 2,
lostStatus: 2,
winConversion: 0.5,
lostConversion: 0.5,
brands: [
{
brandName: 'dell',
winProjects: 1,
conversion: 0.25,
},
{
brandName: 'apple',
winProjects: 1,
conversion: 0.25,
},
],
},
{
period: 2021,
....
}
]
I almost succeeded, but i can't reduce the brands array to the desire structure.
const reduceData = data.reduce((acc, project) => {
const { year, name, status, sales, brand } = project;
if (!acc[year]) {
acc[year] = {
companies: new Set(),
totalProjects: 0,
totalSales: 0,
winStatus: 0,
lostStatus: 0,
winConversion: 0,
lostConversion: 0,
brands: [],
};
}
acc[year].companies.add(brand);
acc[year].uniqueCompanies = [...acc[year].companies].length;
acc[year].totalProjects = (acc[year].totalProjects || 0) + 1;
acc[year].totalSales = acc[year].totalSales += sales;
acc[year].winStatus =
status === 'win' ? acc[year].winStatus + 1 : acc[year].winStatus;
acc[year].lostStatus = acc[year].totalProjects - acc[year].winStatus;
acc[year].winConversion = acc[year].winStatus / acc[year].totalProjects;
acc[year].lostConversion = acc[year].lostStatus / acc[year].totalProjects;
acc[year].brands.push({
brandName: brand,
totalSales: sales,
});
return acc;
}, {})
Please help me understand the logic of it!
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|