Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

307
Views
How to Add the values ​of an object array based on a condition? JS

I am looking to sum the fields of my objects according to a value of my object

For example, i have an array:

   [
    {
        "month": 4,
        "periodDays": 1,
        "expected": 5
    },
    {
        "month": 5,
        "periodDays": 10,
        "expected": 40
    },
    {
        "month": 5,
        "periodDays": 11,
        "expected": 35
    },

    {
        "month": 6,
        "periodDays": 8,
        "expected": 20
    }
]

and i want:

  [
{
    "month": 4,
    "periodDays": 1,
    "expected": 5
},
{
    "month": 5,
    "periodDays": 21,
    "expected": 75
},
{
    "month": 6,
    "periodDays": 8,
    "expected": 20,
},

I know I can use the reducer but I can't make it work with a condition.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use Array.reduce() to create the desired result.

We start by creating a map using the month value as the key. We then initialize the periodDays and expected values to zero.

For each object, we then add the periodDays and expected to get the sum for each.

Finally, we use Object.values() to turn our map into an array:

let input = [ { "month": 4, "periodDays": 1, "expected": 5 }, { "month": 5, "periodDays": 10, "expected": 40 }, { "month": 5, "periodDays": 11, "expected": 35 },  { "month": 6, "periodDays": 8, "expected": 20 } ]

const result = Object.values(input.reduce((acc, { month, periodDays, expected }) => { 
    acc[month] = acc[month] || { month, periodDays: 0, expected: 0 };
    acc[month].periodDays += periodDays;
    acc[month].expected += expected;
    return acc;
}, {}));

console.log('Result:', result)
.as-console-wrapper { max-height: 100% !important; }

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!