0

Example below, getting total math values corresponding to the same values of period_str key.

[
     {math: 40, period_str: "Period 1, 03 2019"},
     {math: 32, period_str: "Period 1, 03 2019"},
     {math: 44, period_str: "Period 1, 02 2020"},
]

Expected output

[
{math: 72, period_str: "Period 1, 03 2020"}
{math: 44, period_str: "Period 1, 02 2020"}
]

Or output (object only)

{math: 72, period_str: "Period 1, 03 2020"}
{math: 44, period_str: "Period 1, 02 2020"}
shim
  • 9,289
  • 12
  • 69
  • 108
okumu justine
  • 350
  • 6
  • 11

1 Answers1

1

You can just use the period_str as a unique key:

const arr = [
 {math: 40, period_str: "Period 1, 03 2019"},
 {math: 32, period_str: "Period 1, 03 2019"},
 {math: 44, period_str: "Period 1, 02 2020"},
]

const out = arr.reduce((a, v) => {
  if(a[v.period_str]) {
    a[v.period_str].math += v.math
  } else {
    a[v.period_str] = v
  }
  return a
}, {})

console.log(Object.values(out))
Kobe
  • 6,226
  • 1
  • 14
  • 35