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

98
Visualizações
How can i get data from an array of object with matching key and combine the other results into array

i want the result below

Given an array

[{
      "date": "JAN",
      "value": 5,
      "weight": 3
  }, {
      "date": "JAN",
      "value": 4,
      "weight": 23
  }, {
      "date": "FEB",
      "value": 9,
      "weight": 1
  }, {
      "date": "FEB",
      "value": 10,
      "weight": 30
  }]

and a key 'date'
transform it into following output:

 [{
       "date": "JAN",
       "value": [5, 4],
       "weight": [3, 23]
   }, {
       "date": "FEB",
       "value": [9, 10],
       "weight": [1, 30]
   }]

any help would be much appreciated thank You in advance

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

0

  • Using Array#reduce, iterate over the array while updating a Map where the primaryKey is the key and the grouped object is the value
  • In every iteration:
    • get the primary-key value and the remaining properties from the current object
    • Using Object#entries, get the list of pairs from the properties
    • Using Map#get, get the current primary-key value if exists
    • If it does, we need to iterate over the entries using Array#forEach and update the arrays
    • If not, we create the initial object and add a new pair using Map#set
  • Finally, using Map#values, you can get the list of grouped objects

const transform = (arr, primaryKey) => 
  [...
    arr.reduce((map, e) => {
    
      const { [primaryKey]: key, ...props } = e;
      const currentProps = Object.entries(props);
      const item = map.get(key);
      
      if(item) {
        currentProps.forEach(([ k, v ]) => item[k] = [...(item[k] ?? []), v]);
      } else {
        const obj = currentProps.reduce((acc, [ k, v ]) => ({
          ...acc, [k]: Array.isArray(v) ? [...v] : [v]
        }), { primaryKey: key });
        map.set(key, obj);
      }
      
      return map;
    }, new Map)
    .values()
  ];


console.log( transform([ { "date": "JAN", "value": 5, "weight": 3 }, { "date": "JAN", "value": 4, "weight": 23 }, { "date": "FEB", "value": 9, "weight": 1 }, { "date": "FEB", "value": 10, "weight": 30 } ], 'date') );
console.log( transform([ { type: '200', api: [ '/counter' ] }, { type: '400', api: [ '/counter' ] }, { type: '500', api: [ '/counter', '/product' ] } ], 'type') );

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