Search code examples
javascriptangularngoninit

How to Sum up the values of 5 diff columns as TOTAL using *ngONinit?


i am having an array of Product with fields name ID,Brand,Price,QtySold,Value where value=Price*qtySold and at the end i need to show Number of Items,Total quantity sold and total sales value

 @Component
({
 selector: 'my-app',
 templateUrl: './app.component.html',
 styleUrls: [ './app.component.css' ]
 }`
export class AppComponent{
allProduct:Product[]=[
{Id:'P104', Brand:'Pepsi',Price:4,qtySold:22},
{Id:'C124', Brand:'Coke',Price:4,qtySold:26},
{Id:'M155', Brand:'Maggie',Price:6,qtySold:10},
{Id:'DM241', Brand:'Cadburys',Price:10,qtySold:15},
{Id:'5S118', Brand:'5 Star',Price:8,qtySold:8},
];

Need to display the Number of Products,Sum of Quantity sold and sum of Sales Value


Solution

  • You will need something like below within your ngOninit

    let products = [
      {
        "Id": "P104",
        "Brand": "Pepsi",
        "Price": 4,
        "qtySold": 22
      },
      {
        "Id": "C124",
        "Brand": "Coke",
        "Price": 4,
        "qtySold": 26
      },
      {
        "Id": "M155",
        "Brand": "Maggie",
        "Price": 6,
        "qtySold": 10
      },
      {
        "Id": "DM241",
        "Brand": "Cadburys",
        "Price": 10,
        "qtySold": 15
      },
      {
        "Id": "5S118",
        "Brand": "5 Star",
        "Price": 8,
        "qtySold": 8
      }
    ];
    
    let productsCount = products.length;
    let qtySold = products.reduce((a, b) => +a + +b.qtySold, 0);
    let sales = products.reduce((a, b) => +a + +b.Price, 0);
    
    console.log(productsCount);
    console.log(qtySold);
    console.log(sales);

    STACKBLITZ DEMO