Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

107
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda