0

I am getting an array of grades from an api but when it try to add them to get the avarege. they get printed instead of added.

this is the array from the api

grades: (8) ["71", "81", "72", "92", "79", "82", "91", "90"]

My code

 student.grades.map((grades) => {
                      var avarge = 0;
                      avarge = avarge + grades;
                      return avarge;
                    })

Output

071081072092079082091090
1

2 Answers 2

2

String concatenation versus numerical addition. Using Number you can cast number-like strings to a number and addition will now work.

Simple array::reduce to reduce an array of values down to a single value.

const grades = ["71", "81", "72", "92", "79", "82", "91", "90"];

const total = grades.reduce((sum, grade) => sum + Number(grade), 0);

console.log('total', total);
console.log('avg', total / grades.length);

Coincidentally you can do some forced conversion as well, by prepending a + to the value to force it to a number, but caution should be used.

const grades = ["71", "81", "72", "92", "79", "82", "91", "90"];

const total = grades.reduce((sum, grade) => sum + +grade, 0);

console.log('total', total);
console.log('avg', total / grades.length);

Sign up to request clarification or add additional context in comments.

1 Comment

thanks you saved my life. I am working on a challenge. thanks!!!
0

Use ParseInt to typecast the strings, You are trying to add the strings. Convert the strings to either Integers or float using parseInt or parseFloat. Then you can able to add the number strings. https://www.tutorialspoint.com/how-to-add-a-number-and-a-string-in-javascript

student.grades.map((grade) => {
  var average = 0;
  average = parseInt(average) + parseInt(grade);
  return average
});

Reduce in javascript

let data = ["71", "81", "72", "92", "79", "82", "91", "90"];
let total = data.reduce(( accumulator, currentValue ) => accumulator + parseInt(currentValue),0);

console.log("Total : "+total)
console.log("Average : "+total / data.length)

2 Comments

this is the output now 7181729279829190
use parseInt to add

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.