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

195
Visualizações
Why does my use of javascript's reduce function return "undefined"

1) I've got an array of objects, called employees.

2) I'm trying to find the highest paid employee in the array.

3) I'm using Javascript's reduce function (inside function findHighestPaid) to do so.

4) Running findHighestPaid(employees) returns "undefined" when I expected it to return the object that has property name: Abelard.

Here's my code.

const employees = [
  {
    name: "Aziz",
    salary: 17050,
  },
  {
    name: "Angela",
    salary: 17060,
  },
  {
    name: "Abelard",
    salary: 17070,
  },
];

function findHighestPaid(arrayOfObjects) {
  let myObject = {
    name: "pretendEmployee",
    salary: 17040,
  };

  arrayOfObjects.reduce(myFunction, myObject);

  function myFunction(acc, item) {
    let personSalary = item.salary;
    let accSalary = acc.salary;
    if (Math.sign(personSalary - accSalary) > 0) {
      console.log(`returning object for ${item.name}`);
      return item;
    } else {
      console.log(`returning object for ${acc.name}`);
      return acc;
    }
  } // end myFunction
}

When I run findHighestPaid(employees) and look in console I see :

returning object for Aziz // (as I expected)

returning object for Angela // (as I expected)

returning object for Abelard // (as I expected)

undefined // (oh oh!!!)

Why does the reduce function return "undefined"?

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

0

the undefined that's being printed at the end is the return value of findHighestPaid() function that you run.

since you're not returning anything it's returning undefined. if your goal is to see the return value of reduce() add a return statement to the function like this:

const employees = [
  {
    name: "Aziz",
    salary: 17050,
  },
  {
    name: "Angela",
    salary: 17060,
  },
  {
    name: "Abelard",
    salary: 17070,
  },
];

function findHighestPaid(arrayOfObjects) {
  let myObject = {
    name: "pretendEmployee",
    salary: 17040,
  };

  return arrayOfObjects.reduce(myFunction, myObject);

  function myFunction(acc, item) {
    let personSalary = item.salary;
    let accSalary = acc.salary;
    if (Math.sign(personSalary - accSalary) > 0) {
      console.log(`returning object for ${item.name}`);
      return item;
    } else {
      console.log(`returning object for ${acc.name}`);
      return acc;
    }
  } // end myFunction
}

console.log(findHighestPaid(employees));

about 4 years ago · Juan Pablo Isaza Relatório

0

Your code is working perfectly although you don't need Math.sign at all, just return the result:

const employees = [
  {
    name: "Aziz",
    salary: 17050,
  },
  {
    name: "Angela",
    salary: 17080,
  },
  {
    name: "Abelard",
    salary: 17070,
  },
];

function findHighestPaid(arrayOfObjects) {
  let myObject = {
    name: "pretendEmployee",
    salary: 17040,
  };

  return arrayOfObjects.reduce(myFunction, myObject);

  function myFunction(acc, item) {
    let personSalary = item.salary;
    let accSalary = acc.salary;
    if (personSalary - accSalary > 0) {
      console.log(`returning object for ${item.name}`);
      return item;
    } else {
      console.log(`returning object for ${acc.name}`);
      return acc;
    }
  } // end myFunction
}

console.log('Highest paid', findHighestPaid(employees));

about 4 years ago · Juan Pablo Isaza Relatório

0

you just have to put it like this

function findHighestPaid(arrayOfObjects) {
    return arrayOfObjects.reduce((prev, curr) => {
        if(!prev) {
            return curr;
        }

        return curr.salary > prev.salary ? curr : prev;    
    }, null);
}

const highestPaidEmployee = findHighestPaid(employees);

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