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

185
Visualizações
Reduce an array of object with same key and concat same property

I have an array of objects in the below form it has three properties serviceName, pool, and environment I want to group the object based on environment and at the same time need to concat the pools:

const data = [
  {
    serviceName: "visa",
    pool: "3g",
    environment: "test-int",
  },
  {
    serviceName: "visa",
    pool: "4g",
    environment: "test-int",
  },
  {
    serviceName: "visa",
    pool: "5g",
    environment: "test-int",
  },
  {
    serviceName: "amex",
    pool: "5g",
    environment: "dev",
  },
  {
    serviceName: "amex",
    pool: "6g",
    environment: "dev",
  },
];

I want the output in the below format:

const output = [
    {
      serviceName: "visa",
      pool: "3g,4g,5g",
      environment: "test-int"
    },
    {
      serviceName: "amex",
      pool: "5g,6g",
      environment: "dev"
    },
  ]

Based on my current code it just returns a single object instead of an array of objects:

const output = data.reduce((acc, ar) => {
      let res = {
        ...acc,
        pool: acc["pool"] + "," + ar.pool
      };
      return res;
    }
  });
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I think the basic problem is that you need to segment out all the elements that match by serviceName and then do your reduce to join the pool value.

Maybe something like this:

const res = [
    {
      serviceName: "visa",
      pool: "3g",
      environment: "test-int"
    },
    {
      serviceName: "visa",
      pool: "4g",
      environment: "test-int"
    },
    {
      serviceName: "amex",
      pool: "5g",
      environment: "dev"
    },
    {
      serviceName: "amex",
      pool: "6g",
      environment: "dev"
    }
  ];

const groupBy = (arr, getKey) => {
  return arr.reduce((memo, item) => {
    const key = getKey(item)
    memo[key] ||= [];
    memo[key].push(item);
    return memo;
    
  }, {})
}

const byServiceName = groupBy(res, ({serviceName}) => serviceName);

const results = Object.values(byServiceName).map((items) => {
   return items.reduce((acc, item) => {
     let res = {
        ...acc,
        pool: acc["pool"] + "," + item.pool
      };
      return res;
    })
});

console.log(results)

The groupBy function could be simplified to not take the getKey function, but that adds a little flexibility. If you know it's always going to be on serviceName, you could instead have something like

const groupByServiceName = (arr) => {
  const key = 'serviceName'
  return arr.reduce((memo, item) => {
    memo[key] ||= [];
    memo[key].push(item);
    return memo;
}, {})
about 4 years ago · Juan Pablo Isaza Relatório

0

Here is a method that generates an object with environment value as key and then extracts its values into array

const data = [
  {
    serviceName: "visa",
    pool: "3g",
    environment: "test-int",
  },
  {
    serviceName: "visa",
    pool: "4g",
    environment: "test-int",
  },
  {
    serviceName: "visa",
    pool: "5g",
    environment: "test-int",
  },
  {
    serviceName: "amex",
    pool: "5g",
    environment: "dev",
  },
  {
    serviceName: "amex",
    pool: "6g",
    environment: "dev",
  },
];

const output = Object.values(data.reduce((acc, ar) =>
{
  if (acc[ar.environment])
    acc[ar.environment].pool += "," + ar.pool;
  else
    acc[ar.environment] = {...ar};

  return acc;
},{}));

console.log(output);

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