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

158
Visualizações
javascript to group array of objects by key

I am trying to group an array of objects like the below using JavaScript.

const array = [
  { 'red':  50 , 'green':99 , 'blue': 66},
  {'blue':65, 'red': 88 }, 
  { 'green':9 , 'blue': 6},
  { 'red':  650 , 'green':959 , 'blue': 663},
];

and expecting the below result,

{
    red: [50, 88, 650],
    green: [99,9,959],
    blue: [66,65, 6, 663]
}

Can we implement this using Reduce function?

Thanks in advance!.

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You can try the below approach to do so. Hope it helps

Loop through the array and it's items. If the key already exists inside the outputObj object push the new value into the respective array, else simply create a new array with that key and value (outputObj[key] = [item[key]]).

Working code:

const array = [{
    'red': 50,
    'green': 99,
    'blue': 66
  },
  {
    'blue': 65,
    'red': 88
  },
  {
    'green': 9,
    'blue': 6
  },
  {
    'red': 650,
    'green': 959,
    'blue': 663
  },
];

//Method 1
const outputObj = {};

array.forEach(item => {
  Object.keys(item).forEach(key => {
    if (key in outputObj) {
      outputObj[key].push(item[key])
    } else {
      outputObj[key] = [item[key]]
    }
  })
})

console.log(outputObj)

//Method 2
const finalObj = array.reduce((acc, curr) => {
  const obj = Object.keys(acc).length ? acc : {}
  Object.keys(curr).forEach(key => {
    if (key in obj) {
      obj[key].push(curr[key])
    } else {
      obj[key] = [curr[key]]
    }
  })
  return obj;
}, {})

console.log(finalObj)

about 4 years ago · Juan Pablo Isaza Relatório

0

  array = [
    { red: 50, green: 99, blue: 66 },
    { blue: 65, red: 88 },
    { green: 9, blue: 6 },
    { red: 650, green: 959, blue: 663 },
  ];
  
  let result = {};
    for (let item of this.array) {
      for (const [key, value] of Object.entries(item)) {
        if (!result.hasOwnProperty(key)) {
          result[key] = [value];
        } else {
          result[key].push(value);
        }
      }
    }
    
    console.log(result);

about 4 years ago · Juan Pablo Isaza Relatório

0

This piece of code will fill the result object grouping values coming from the same key in the array variable:

var result = {};

array.forEach(
  item => Object.keys(item).forEach(
        key => {
            if (result[key] === undefined) result[key] = [];
            result[key].push(item[key]);
        }
  )
)
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