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

204
Visualizações
Rewriting reduce callback to stop reassigning accumulator

I have a function written like so:

 type ChartData = {
    x?: number[],
    y?: number[],
    z?: number[],
  };

  const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

  const formattedData = data.reduce((acc, el) => {
    Object.entries(el!).forEach(([k, v]) => {
      acc = { ...acc, [k]: [...(acc[k as keyof ChartData] || []), v] };
    });

    return acc;
  }, {} as ChartData);

This code does what I want, but I'm getting an eslint error: no-param-reassign.

I know that I could disable the rule, but I wondered if there's a better way of writing this reduce callback so that I am not reassigning acc.

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

This 'no-param-reassign' warning mean that you have modified the function params inside the function. So here maybe a workaround for this warning.

type ChartData = {
  x?: number[],
  y?: number[],
  z?: number[],
};

const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

const formattedData = data.reduce((acc, el) => {
  let newAcc = { ...acc };
  Object.entries(el!).forEach(([k, v]) => {
    newAcc = { ...newAcc , [k]: [...(newAcc [k as keyof ChartData] || []), v] };
  });

  return newAcc ;
}, {} as ChartData);
about 4 years ago · Santiago Trujillo Relatório

0

You can assign to acc[k] directly:

const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

const formattedData = data.reduce((acc, el) => {
  Object.entries(el).forEach(([k, v]) => {
    acc[k] = (acc[k] || []).concat(v);
  });
  return acc;
}, {});

console.log(formattedData);

More code but also more efficient (fewer allocations and copies):

const data = [{ x: 1, y: 2, z: 3 }, { x: 4, y: 7, z: 10 }];

const formattedData = data.reduce((acc, el) => {
  Object.entries(el).forEach(([k, v]) => {
    if (!acc[k]) {
      acc[k] = [];
    }
    acc[k].push(v);
  });
  return acc;
}, {});

console.log(formattedData);

about 4 years ago · Santiago Trujillo 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