Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

382
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda