Calculation inside a array of objects

I have the following array of objects like this

let items = [
    {
        key: 1,
        name: 'abc',
        quanitity: 2,
        rate: 10
    },
    {
        key: 2,
        name: 'abc 12',
        quanitity: 4,
        rate: 14
    },
    {
        key: 3,
        name: 'abc',
        quanitity: 12,
        rate: 12
    } ]

now what I am doing is making a cart, now I want to display the total sum at the bottom based on the array. like this will return 2 * 10 + 4 * 14 + 12 * 12 = totalAmount.

this is what I tried using forEach

let dd = p.forEach((x) => {
        let totalAmount = 0;

      if (totalAmount === 0) {
        let cal = Number(x.quantity) * Number(x.rate);
        totalAmount = totalAmount + cal;
      } else {
        let cal2 = Number(x.quantity) * Number(x.rate);
        totalAmount = cal2;
      }
      console.log("cal  sdda", totalAmount);

      return totalAmount;
    });

I used forEach but I am not getting the desired output, as well as used reduce but I know that won’t work. Any help

Answer

Using Array#reduce:

const items = [
  { key: 1, name: 'abc', quanitity: "2", rate: "10" },
  { key: 2, name: 'abc 12', quanitity: "4", rate: "14" },
  { key: 3, name: 'abc', quanitity: "12", rate: "12" }
];

const totalAmount = items.reduce((total, { quanitity=0, rate=0 }) =>
  total + (+quanitity * +rate)
, 0);

console.log(totalAmount);

Using Array#forEach:

const items = [
  { key: 1, name: 'abc', quanitity: "2", rate: "10" },
  { key: 2, name: 'abc 12', quanitity: "4", rate: "14" },
  { key: 3, name: 'abc', quanitity: "12", rate: "12" }
];

let totalAmount = 0;
items.forEach(({ quanitity=0, rate=0 }) =>
  totalAmount += (+quanitity * +rate)
);

console.log(totalAmount);

Leave a Reply

Your email address will not be published. Required fields are marked *