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

151
Views
Transform array of objects to another array of objects with unique id-s and array of names

How to transform this items array to result array (objects should be with unique id and have key 'names' with array of name properties from objects with the same id):

Original array:

const items = [
{id: 1, name: 'a'}, 
{id: 2, name: 'b'}, 
{id: 3, name: 'c'}, 
{id: 1, name: 'd'}, 
{id: 3, name: 'f'}
];

Transformed array:

const result = [
{id: 1, names: ['a', 'd']}, 
{id: 2, names ['b']}, 
{id: 3, names: ['c', 'f']}
];
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use Array.reduce to get the result.

const inputArray = [
  {id: 1, name: 'a'}, 
  {id: 2, name: 'b'}, 
  {id: 3, name: 'c'}, 
  {id: 1, name: 'd'}, 
  {id: 3, name: 'f'}
];

const result = inputArray.reduce((acc, item) => {
   const exist = acc.find(e => e.id == item.id);
   // check exist in result
   if (exist) {
      // exist: push 'name' value to 'names' array
      exist['names'].push(item.name);
   } else {
      // not exist: create new item in result
      acc.push({
         'id': item.id,
         'names': [item.name]
      });
   }
   
   return acc;
}, []);

console.log(result);

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!