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

132
Views
Group keys of an object in array

I have an array :

let x = [{name: 'x1', value: 2}, {name: 'x2', value: 3}, {name: 'y1', value: 4}, {name: 'z1', value: 1}];

I need to group few keys based on some condition and get their sum

res = [{
name: ['x1, y1'],
value: 6
},
{
name: [x2],
value: 3
},
{
name: [z1],
value: 1
}]
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

You can take a number of grouped items and consider them as separate groups.

const
    groups = [['x1', 'y1']],
    data = [{ name: 'x1', value: 2 }, { name: 'x2', value: 3 }, { name: 'y1', value: 4 }, { name: 'z1', value: 1 }],
    result = Object.values(data.reduce((r, { name, value }) => {
        const key = groups.find(a => a.includes(name))?.join('|') || name;
        r[key] ??= { name: [], value: 0 };
        r[key].name.push(name);
        r[key].value += value;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

about 4 years ago · Juan Pablo Isaza Report

0

You can do that this way:

let res = [
    {
        name: ["x1", "y1"],
        value: 0
    },
    [...]
]

res.forEach(group => {
    x.forEach(row => {
        if (group.name.indexOf(row.name) !== -1) {
            group.value += row.value;
        }
    });
})
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!