Intento aprender más sobre los métodos de matriz y también sobre cómo trabajar con objetos. Se me ocurre este ejemplo ficticio que simula datos entrantes.
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, }, ]Me gustaría manipular la información para poder crear una nueva matriz como esta:
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, .... } ]Casi lo logro, pero no puedo reducir la matriz de marcas a la estructura de deseos.
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; }, {})¡Por favor, ayúdame a entender la lógica de esto!