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
Zaid
  • 29
  • 6
  • 1
    You should use reducer instead of the map: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce and then divide it on the amount of the elements from that array – haik.ampardjian Jul 22 '20 at 10:34

2 Answers2

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);
Drew Reese
  • 165,259
  • 14
  • 153
  • 181
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)
Jeeva
  • 1,550
  • 12
  • 15