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

252
Views
Merge arrays based on a condition

Ok i have a array like the following

[
  {data: Array(22), title: '1111'}
  {data: Array(12), title: '2222'}
  {data: Array(6), title: '1111'}
  {data: Array(22), title: '3333'}
  {data: Array(0), title: '4444'}
]

What i want to do this if there are objects with duplicate titles (like {data: Array(22), title: '1111'} and {data: Array(6), title: '1111'}), i want to merge the data arrays of the objects with equal titles.

So my final output should be like

[
  {data: Array(28), title: '1111'}
  {data: Array(12), title: '2222'}
  {data: Array(22), title: '3333'}
  {data: Array(0), title: '4444'}
]

I have tried some lodash functions as well and also javascript filter. I tried forEach ,mapping and etc. But cannot grasp the method to do what i need.

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

0

You can use Array#reduce.

let arr = [
  {data: [1,2,3], title: '1111'},
  {data: [4,5], title: '2222'},
  {data: [6], title: '1111'},
  {data: [7,8,9,10], title: '3333'},
  {data: [11,12,13,14,15], title: '4444'}
]
let res = Object.values(arr.reduce((acc, {title, data})=>{
    (acc[title] ??= {title, data: []}).data.push(...data);
    return acc;
}, {}));
console.log(res);

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!