-2

I want sum all value in object of array, the problem is if array length more than 2, the output will be NaN. so this code.

data:

const data = [ 
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 10}
]

solve code:

console.log(data.reduce((p,c) => p.price+c.price))
> 15

If i add more object to the data

const data = [ 
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 10}
]

console.log(data.reduce((p,c) => p.price+c.price))
> NaN

so i try to flatten data:

console.log(data.map(o) => o.reduce((p,c) => p+c))
> 20

It possible, but is there any effective solutions? Thank you.

Pengguna
  • 4,636
  • 1
  • 27
  • 32

2 Answers2

3

The problem is what you're thinking about the accumulator in the function reduce, the accumulator is the last processed value by the handler, in your case is a number and you're trying to sum a property price from a number + the current property price from param c. Further, you need to pass the initial value, in this case, 0.

So, you need to use the accumulator as a number rather than an object with a property price:

const data = [ 
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d199ce7c1366e5ce7d", "price": 10}
]

console.log(data.reduce((p,c) => p + c.price, 0));
Ele
  • 33,468
  • 7
  • 37
  • 75
2

you should use the function hander inside this method

const data = [ 
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 5},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 3},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 11},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 9},
  { "id": "5ad772d19f9ce7c1366e5ce7d", "price": 7}
]

const res = data.reduce((total, amount) => {

  total.price += amount.price;
  console.log(total.price);
  return total;
});
console.log('total: ' + res.price);

good luck ;)