Guest User

Untitled

a guest
Dec 16th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.75 KB | None | 0 0
  1. // before
  2. let objArr = [
  3. {
  4. date: '01/01/2018'
  5. total: 1
  6. },
  7. {
  8. date: '01/01/2018'
  9. total: 2
  10. },
  11. {
  12. date: '01/02/2018'
  13. total: 3
  14. },
  15. {
  16. date: '01/02/2018'
  17. total: 4
  18. },
  19. ...
  20. ]
  21.  
  22. // final result
  23. let finalArr = [
  24. {
  25. date: '01/01/2018'
  26. total: 3
  27. },
  28. {
  29. date: '01/02/2018'
  30. total: 7
  31. },
  32. ...
  33. ]
  34.  
  35. objArr.reduce((acc, obj) => {
  36. acc.set(obj.date, (acc.get([obj.date]) || 0) + obj.total);
  37. return acc;
  38. }, new Map())
  39.  
  40. // bad output
  41. badArray = [
  42. ...,
  43. {
  44. date: '01/02/2018'
  45. total: 4
  46. },
  47. {
  48. date: undefined
  49. total: NaN
  50. },
  51. {
  52. date: undefined
  53. total: NaN
  54. }
  55. ]
Add Comment
Please, Sign In to add comment