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

374
Views
Combining 2 arrays of objects into 1 array of objects (refactoring request)

Looking for more optimized way to do it.

Resource arrays:

const users = [
    { id: 1, name: 'Vasya', postIds: [11, 22] },
    { id: 2, name: 'Petya', postIds: [33] },
    { id: 3, name: 'Roma', postIds: [44] },
];

const posts = [
    { id: 11, title: 'How to eat' },
    { id: 22, title: 'How to drink' },
    { id: 33, title: 'How to breath' },
    { id: 44, title: 'How to swim' },
];

Expected result

   const expectedResult = [
      {
        id: 1,
        name: 'Vasya',
        posts: [
          { id: 11, title: 'How to  eat' },
          { id: 22, title: 'How to drink' },
        ]
      },
      {
        id: 2,
        name: 'Petya',
        posts: [{ id: 33, title: 'How to breath' },]
      },
      {
        id: 3,
        name: 'Roma',
        posts: [{ id: 44, title: 'How to swim' }]
      },
    ]

What i am doing:

const expectedOutput = users.map(({id,name,postIds})=>({id,name,posts:posts.filter(post=>postIds.includes(post.id))}))

The problem is - i am doing too many iterations (map, filter and includes), thinking that, there is a possibility to do it in a more pretty way. Will be greatful for any ideas for refactoring

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

0

Your solution seems fine, but if you wanted to cut down on complexity you can first create a lookup table of posts and then map against it.

Here using a Map for the lookup table, nested map() calls to iterate over each object/postIds array, and a nullish ?? check to return an object with just id if no matching post is found.

const users = [
  { id: 1, name: 'Vasya', postIds: [11, 22] },
  { id: 2, name: 'Petya', postIds: [33] },
  { id: 3, name: 'Roma', postIds: [44] },
];

const posts = [
  { id: 11, title: 'How to eat' },
  { id: 22, title: 'How to drink' },
  { id: 33, title: 'How to breath' },
  { id: 44, title: 'How to swim' },
];

const postsMap = new Map(posts.map((post) => [post.id, post]));

const result = users.map(({ postIds, ...user }) => ({
  ...user,
  posts: postIds.map((id) => postsMap.get(id) ?? { id }),
}));

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

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!