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

108
Visualizações
Naive approach to summarize array of objects?

I faced a challenge where I needed to summarize an array of objects by the object's keys. I found a solution, but I can't shake off the feeling, that my approach is pretty naive:

const objArr = [
    { id: 1, val: "🍊" },
    { id: 1, val: "🍇" },
    { id: 1, val: "🍎" },
    { id: 2, val: "🥦" },
    { id: 2, val: "🌽" },
    { id: 2, val: "🌶" },
];

let tempArr = [];
let uniqueIdArr = [];
let sortedArr = [];

objArr.forEach((obj) => {
    tempArr.push(obj.id);
    uniqueIdArr = [...new Set(tempArr)];
});

uniqueIdArr.forEach((uniqueId) => {
    let arr = [];
    objArr.forEach((obj) => {
        if (obj.id == uniqueId) {
            arr.push(obj.val);
        }
    });
    sortedArr.push({
        id: uniqueId,
        vals: arr,
    });
});

console.log(sortedArr);
// Output: [{ id: 1, vals: [ '🍊', '🍇', '🍎' ] }, { id: 2, vals: [ '🥦', '🌽', '🌶' ] }]

Maybe there is something I don't know about JavaScript's array methods yet? Is this approach totally wrong? Is there another way, so that I could reduce the code and make it more elegant?

So many questions...

Any hint or explanation would be much appreciated. 🙈

Thanks in advance

J.

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

0

Side note: normally, you're supposed to have unique id, other than that, you're doing multiple passes over the source array, which means in worse-case scenario (when there are no duplicate id's) you get O(n²) time complexity, hence execution time will spike rapidly as the number of items in array grows.

If you seek to optimize the performance, you may probably employ Map together with Array.prototype.reduce(), like this:

const objArr = [
    { id: 1, val: "🍊" },
    { id: 1, val: "🍇" },
    { id: 1, val: "🍎" },
    { id: 2, val: "🥦" },
    { id: 2, val: "🌽" },
    { id: 2, val: "🌶" },
]

const grouppedArr = [
  ...objArr
    .reduce((acc, {id, val}) => {
      const group = acc.get(id)
      group
        ? group.vals.push(val)
        : acc.set(id, {id, vals:[val]})
      
      return acc
    }, new Map)
    .values()
]

console.log(grouppedArr)

about 4 years ago · Juan Pablo Isaza Relatório

0

you can use Array.prototype.reduce to make your code bit shorter:

const objArr = [
    { id: 1, val: "🍊" },
    { id: 1, val: "🍇" },
    { id: 1, val: "🍎" },
    { id: 2, val: "🥦" },
    { id: 2, val: "🌽" },
    { id: 2, val: "🌶" },
];

let result = objArr.reduce((acc,e) => {
    let idx = acc.findIndex(s => s.id === e.id)
    if(idx > -1){
        acc[idx].vals.push(e.val)
    }
    else{
        acc.push({id:e.id,vals:[e.val]})
    }
    return acc
},[])


console.log(result)

about 4 years ago · Juan Pablo Isaza Relatório

0

Your ideas are good and explicit, but far from being optimal.

const objArr = [
    { id: 1, val: "🍊" },
    { id: 1, val: "🍇" },
    { id: 1, val: "🍎" },
    { id: 2, val: "🥦" },
    { id: 2, val: "🌽" },
    { id: 2, val: "🌶" },
];
const idValMap = new Map();

objArr.forEach(o=>{
   let vals = idValMap.get(o.id);
   if(!vals){
       vals = [];
       idValMap.set(o.id,vals);
   }
   vals.push(o.val);
});

console.log(Array.from(idValMap.entries()));

You can do most of it in just one loop. Take the key, check if you saw it already, if not initialize. That's it

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