1

I am working with ReactJS. I have a JSON Object like this:

[
  {
    "id": "1",
    "category": "cellphones",
    "name": "Xiaomi Redmi Note 10",
    "stock": "99",
    "price": "100",
    "quantity": "3"
  },
  {
    "id": "2",
    "category": "cellphones",
    "name": "Iphone 11",
    "stock": "3",
    "price": "1000",
    "quantity": "5"
  },
  {
    "id": "3",
    "category": "laptops",
    "name": "MSI GF65 Thin",
    "stock": "40",
    "price": "2000",
    "quantity": "2"
  }
]

And i want to get the overall total of this items by doing something like this:

const getAllTotal = () => {
  const sum = cartItems.reduce(
    (prev, next) => prev.quantity * prev.price + next.quantity * next.price,
    0
  );
  console.log(sum);
  return sum;
};

The thing is, everytime i call that function, the console returns NaN.

I first thought it was caused by the type of the keys, so i tried to enclose said keys into the parseInt() method, but it returned the same NaN. What am i doing wrong?

Ali Nauman
  • 1,374
  • 1
  • 7
  • 14
  • Does this answer your question? [How to call reduce on an array of objects to sum their properties?](https://stackoverflow.com/questions/5732043/how-to-call-reduce-on-an-array-of-objects-to-sum-their-properties) – Emre Aug 04 '23 at 20:00
  • it might be that your prices and quantities are strings and not numbers to begin with. you can convert the values in your function, or its probably easier to just make the price and quantities in the json object a number – mrtomblue Aug 04 '23 at 20:01
  • 2
    Try it: `cartItems.reduce( ( sum, { price } ) => sum + price , 0)` – Emre Aug 04 '23 at 20:02

1 Answers1

4

I think you are not using array.reduce() method properly. Here is the correct form try this:

const getAllTotal = () => {
  const sum = cartItems.reduce(
    (prev, next) => prev + next.quantity * next.price,
    0
  );
  console.log(sum);
  return sum;
};

Take a look at this link for proper implementation of array.reduce() method

Ali Nauman
  • 1,374
  • 1
  • 7
  • 14
Ahmer Saud
  • 130
  • 10
  • The reason your code returns NaN beacause the first initial value is 0 and 0.price , 0.quantity is NaN, and NaN + integer returns NaN – Ahmer Saud Aug 04 '23 at 20:09
  • 1
    You were right, i changed the JSON strings with numbers into plain numbers, tried your code and it worked like a charm. Thank you! – Emanuel Rodriguez Aug 04 '23 at 20:15