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

232
Visualizações
How to define a function in javascript reduce function?

I have an object student, it has property id, name, groupName. allStudents is the array of student objects, I want to turn it to an id to student map, but for each student, I want to generate a new property "label", if the student has groupName, label value is "name + groupName", otherwise it is name. So I write below code, it works:

const idsToStudents = allStudents.reduce((tempMap, student) => {
    const getStudentLabel = (student) => {
        if (student.groupName) {
            return [student.name, `(${student.groupName})`].join(' ');
        }
        return student.name;
    };
    const studentLabel = getStudentLabel(student);
    return {
        ...tempMap,
        [student.id]: { ...student, label: studentLabel}
    };
}, {});

I define getStudentLabel function inside reducer function, is there a better way to do this instead of declare getStudentLabel function again and again in the reducer function? You can ignore what exactly getStudentLabel does, just think it takes each person as parameter and return something based on person, is there a way to define the function only once, but still I can call it for each person in the reducer?

Thank you!

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

0

You are passing student as a parameter to the function, so you don't need to declare it inside the reduce. This would work as well:

const getStudentLabel = (student) => {
  if (student.groupName) {
    return [student.name, `(${student.groupName})`].join(' ');
  }
  
  return student.name;
};

const idsToStudents = allStudents.reduce((tempMap, student) => {
  const studentLabel = getStudentLabel(student);
  return {
      ...tempMap,
      [student.id]: { ...student, label: studentLabel}
  };
}, {});

And you can also shorten the code a bit:

const getStudentLabel = ({ name, groupName }) => groupName
  ? `${name} (${groupName})`
  : name;

const idsToStudents = allStudents.reduce((tempMap, student) => ({
  ...tempMap,
  [student.id]: { ...student, label: getStudentLabel(student) }
}), {});
about 4 years ago · Juan Pablo Isaza Relatório

0

I wouldn't worry about redefining functions inside closures. Any reasonable javascript implementation will optimize that so that minimal extra memory is being used. I wouldn't say its accurate to say that you're "defining" the function more than once - you are only defining it once in your code. The function is being instantiated each time, but this instantiation will take advantage of caches of the static parts of the the function. So your way of doing it is perfectly fine. As Ori Drori mentioned, you don't have to have the student variable in the inner function, but it might be a good idea to anyway, so that you're very explicit about the function's dependencies.

about 4 years ago · Juan Pablo Isaza Relatório

0

Object.fromEntries can work instead of reduce.

const getStudentLabel = ({name, groupName}) => groupName
  ? name + ` (${groupName})`
  : name;

const idsToStudents = Object.fromEntries(
  allStudents.map(student => [student.id, { ...student, label: getStudentLabel(student) }])
);
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