I’m using React JS, and I’m trying to find the average of this array:
[
"75.0%",
"50.0%",
"66.66666666666666%",
"66.66666666666666%",
"33.33333333333333%",
"58.333333333333336%",
"50.0%",
"66.66666666666666%",
"41.66666666666667%",
"75.0%",
"41.66666666666667%",
"50.0%",
"50.0%",
"72.72727272727273%"
]
Here’s my current code:
const percentCorrects = [
"75.0%",
"50.0%",
"66.66666666666666%",
"66.66666666666666%",
"33.33333333333333%",
"58.333333333333336%",
"50.0%",
"66.66666666666666%",
"41.66666666666667%",
"75.0%",
"41.66666666666667%",
"50.0%",
"50.0%",
"72.72727272727273%"
]
const sum = percentCorrects.reduce((accumulator, currentValue) => {
return accumulator + currentValue
}, 0);
const averaged = sum / percentCorrects.length;
console.log("averaged", averaged);
Right now, my console shows
averaged NaN
Which I looked it up: "The NaN global property is a value representing Not-A-Number"
How do you recommend I fix my code?
I want to be able to display an averaged percentage on my UI, for example: "Average Percent Correct: 48%"
Please let me know how I could fix my code. Thank you
2
Answers
Your issue is that your percentages are not numbers, they’re strings.
Try console logging your value
sum
and you’ll see it’ll look like"75.0%50.0%66.66..."
. This is because in JavaScript the+
operator will concatenate strings.Then when you divide a string by a number, you’ll get a NaN. (Try
console.log("foo"/2)
)You’ll need to first convert those percentages in to numbers.
The
parseFloat
function can do this for you.Your array contains strings, so the
reduce
is concatenating strings, not adding numbers, you can useparseFloat
to fix this:And while you don’t have to trim the
%
from the strings when usingparseFloat
(it won’t consider them when parsing the string), you could useString.prototype.slice
in order to trim those percentage signs off. So your return statement would look like this: