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

262
Vistas
eliminate a variable for an accumulation operation

The following code produces the desired result but is there a way to refactor it to eliminate the accumulator variable?

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const accumulator = {};

data.forEach(o => {
  accumulator[o.id] = { ...accumulator[o.id] , ...o } || o;
});

console.log(accumulator);

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

The built-in method reduce already does this. Pass the accumulator as the second argument. The first argument in the callback is the accumulated value. The second is the current object in this iteration. Return value of callback is passed to next iteration as the accumulated value.

const data = [
    { id: "428", date: "2017-01-24" },
    { id: "526", date: "2022-01-01" },
    { id: "428", name: "George" },
    { id: "526", name: "Sam" },
    { id: "827", name: "Dan" },
];
    
const result = data.reduce((accumulator, o) => {
    accumulator[o.id] = { ...accumulator[o.id] , ...o } || o;
        
    return accumulator;
}, {});
    
console.log(result);

about 4 years ago · Juan Pablo Isaza Denunciar

0

The || o part doesn’t make sense (objects are always truthy), and the repeated spread can become a serious performance trap. It’s also good practice to start with Object.create(null) when using an object as a map to avoid keys colliding with things on Object.prototype (even though it looks like you have numeric keys for the moment).

So, let’s restart from this more efficient and reliable version:

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const accumulator = Object.create(null);

data.forEach(o => {
  Object.assign(accumulator[o.id] ??= {}, o);
});

console.log(accumulator);

With that in mind, here’s how you would use Array.prototype.reduce:

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const accumulator = data.reduce(
  (accumulator, o) => {
    Object.assign(accumulator[o.id] ??= {}, o);
    return accumulator;
  },
  Object.create(null)
);

console.log(accumulator);

about 4 years ago · Juan Pablo Isaza Denunciar

0

You can reduce the dataset using Array.prototype.reduce. Just find the previous object by the id key in the accumulator (acc) or use a new object, and spread the current object over it.

const data = [
  { id: "428", date: "2017-01-24" },
  { id: "526", date: "2022-01-01" },
  { id: "428", name: "George" },
  { id: "526", name: "Sam" },
  { id: "827", name: "Dan" }
];

const reduceBy = (data, predicate) =>
  data.reduce((acc, obj) =>
    (key => ({
      ...acc,
      [key]: {
        ...(acc[key] ?? {}),
        ...obj
      }
    }))
    (typeof predicate === 'string'
      ? obj[predicate]
      : predicate(obj)
    ), {});

const reducedData = reduceBy(data, ({ id }) => id); // or reduceBy(data, 'id')

console.log(reducedData);
.as-console-wrapper { top: 0; max-height: 100% !important; }

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