Why my reduce() function is not unable to find out correct maxGrade? Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Why my reduce() function is not unable to find out correct maxGrade? without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I’m trying to find out the correct Max grade from a given numbers list. So, when i use this highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6") the function gives me 6 as maxGrade but it should be 542.

Please, check the code and explain the problem.

function highAndLow(numbers) {
  var num = numbers.split(" ");

  var maxGrade = num.reduce((accum, currVal) => {
    if (accum > currVal) return accum;
    return currVal;

  });
  console.log(maxGrade);
  console.log(num);
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")

Answer

When you use split() to convert the string to an array, you actually have an array of strings

You can use Array.map(Number) to convert strings into number

The string value "6" is greater than the string value "542"

function highAndLow(numbers) {
  var num = numbers.split(" ").map(Number);

  var maxGrade = num.reduce((accum, currVal) => {
    if (accum > currVal) return accum;
    return currVal;
  });
  console.log(maxGrade);
  console.log(num);
}

highAndLow("4 5 29 54 4 0 -214 542 -64 1 -3 6 -6")
We are here to answer your question about Why my reduce() function is not unable to find out correct maxGrade? - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji