1

Following is my array -

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}]

console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // 6 -> Correct

But if array contains more than 2 items it is throwing NaN as a result, Let me know what I am doing wrong here.

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}]
console.log(products.reduce((acc, product) => acc.quantity + product.quantity)) // NaN -> InCorrect
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Nesh
  • 2,389
  • 7
  • 33
  • 54

4 Answers4

6

The accumulator's initial value, by default, is the first element in the array. If the first element is an object, then adding anything to the object will result in NaN.

Simply provide another argument to reduce to provide the initial value for the accumulator, and ensure the accumulator logs the sum:

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}];

const total = products.reduce((acc, product) => acc + product.quantity, 0);
console.log(total);

If you really wanted to have the accumulator store an object instead, you could do that, but it would mutate the first element in the array, you would have to make sure to access the appropriate property in order to log it:

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}]
console.log(products.reduce((acc, product) => {
  acc.quantity += product.quantity;
  return acc;
}).quantity) 

But that's a really bad idea.

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
5

Cause acc is 6 the second time, acc.quantity is undefined. To solve this, replace acc.quantity with acc and use 0 as a starting accumulator

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
1

The reduce() method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

In your acc variable it contain value not object you directly add with new quantity like this

DEMO

const products = [{
  id: "1",
  quantity: 3
}, {
  id: "2",
  quantity: 3
}, {
  id: "3",
  quantity: 4
}];

let result = products.reduce((acc, {quantity}) => acc +quantity, 0);

console.log(result)
.as-console-wrapper {  max-height: 100% !important;  top: 0;}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44
1

This works perfectly fine

<script>
       const products = [{id: "1", quantity: 3},{id: "2", 
       quantity: 3},{id: "3", quantity: 4}];  

       total = Object.values(products).reduce((t, n) => t       
      + n.quantity, 0);

    console.log(total);
    </script>