I was looking at this Javascript code to calculate the average grade of an array of students and then based on the result decide which letter grade should be assigned. I was wondering how would you display these two results in your HTML? I've played around and tried a few things but nothing seems to work. I'm also new to Javascript so the solution is most likely very simple but I'm just not sure how to go about it.
var students = [80, 77, 88, 95, 68];
var Avgmarks = 0;
for (var i = 0; i < students.length; i++) {
Avgmarks += students[i][1];
var avg = (Avgmarks / students.length);
}
console.log("Average grade: " + (Avgmarks) / students.length);
if (avg < 60) {
console.log("Grade : F");
} else if (avg < 70) {
console.log("Grade : D");
} else if (avg < 80) {
console.log("Grade : C");
} else if (avg < 90) {
console.log("Grade : B");
} else if (avg < 100) {
console.log("Grade : A");
}
EDIT: 09/10/2019
I have revised my code to this:
let students = [80, 77, 88, 95, 68];
let avgMarks = 0;
for (let i = 0; i < students.length; i++) {
avgMarks += students[i];
}
let avg = avgMarks / students.length;
if (avg <= 60) {
document.write("Grade : F");
}
else if (avg <= 70) {
document.write("Grade : D");
}
else if (avg <= 80) {
document.write("Grade : C");
}
else if (avg <= 90) {
document.write("Grade : B");
} else {
document.write("Grade : A");
}
document.getElementById("studentAvgGrade").innerHTML = avg;
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Average Student Grade and Letter Grade</title>
</head>
<body>
<div id="studentAvgGrade"></div>
</body>
</html>
My code is now working. Thank you everyone for your help.
I would however like to know if this is the best way to go about solving the task using pure Javascript or is there a better way?
You can set the element with
const element = document.querySelector(YOUR HTML ELEMENT SELECTOR);
Then inside each if statement
element.innerText = grade
First declare a new variable for grade:
let grade = ""
then inside of your if/else statement variable grade gets assigned a new value with each condition.
in your html select the element where you would want it to appear and then assign variable grade as its innerhtml.:
<h1 id='grading'></h1>
and in your js:
let grade = ""
if (avg < 60){
console.log("Grade : F");
grade = "F"
}
else if (avg < 70) {
console.log("Grade : D");
grade = "D"
}
else if (avg < 80)
{
console.log("Grade : C");
grade = "C"
} else if (avg < 90) {
console.log("Grade : B");
grade = "B"
} else if (avg < 100) {
console.log("Grade : A");
grade = "A"
}
const gradeToDisplay = document.getElementById("grading")
grading.innerHTML = grade
Related
As a recent assignment for my coding bootcamp, we've been asked to create a function that takes an array of numbers as an argument and outputs them to an array of letter grades. I am stuck!
I've tried re-working and refactoring my code, changing the placement of different parts of the program, looking through MDN...
let grades = []
function getLetterGrades(grades) {
let grade = grades.map
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
console.log(grades);
}
getLetterGrades([95, 85, 71]);
The results will only output the numbers I've entered into the function call.
You are using .map() wrong. What you are doing is comparing the map method to a number. You are not executing anything.
function getLetterGrades(grades) {
return grades.map(function(grade) {
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
});
}
var letters = getLetterGrades([95, 85, 71]);
console.log(letters)
Your main issue is this:
let grade = grades.map
You are not invoking the .map method with (), so instead grade is winding up holding a reference to the native map function. And, that function isn't a number, so none of your conditions become true, so you continue past the if statement and just log the array that you passed in.
Instead, you must invoke .map() and supply its required parameter (a function that will be called for each item in the source array). Your if statement should be the body of that function:
let grades = []
function getLetterGrades(grades) {
let letterGrades = grades.map(function(grade){
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
});
console.log(letterGrades);
}
getLetterGrades([95, 85, 71]);
Look at this solution:
let grades = []
function getLetterGrades(grades) {
// add an array (grade) that will hold the output
let grade = []
// iterate over grades with forEach()
grades.forEach(item => {
// item will be equal 95 on the first iteration
// 85 on the second, and 71 on the third - these
// values come from the passed 'grades' parameter
if (item < 60) {
grade.push("F");
} else if (item < 70) {
grade.push("D");
} else if (item < 80) {
grade.push("C");
} else if (item < 90) {
grade.push("B");
} else if (item < 100) {
grade.push("A");
}
})
// console.log(grade) - NOT grades!
console.log(grade);
}
getLetterGrades([95, 85, 71]);
The problem was not with the method you chose - the problem was you didn't finish your function. Here's another solution with map():
let grades = []
function getLetterGrades(grades) {
let grade = grades.map(item => {
if (item < 60) {
return "F";
} else if (item < 70) {
return "D";
} else if (item < 80) {
return "C";
} else if (item < 90) {
return "B";
} else if (item < 100) {
return "A";
}
})
// console.log(grade) - NOT grades!
console.log(grade);
}
getLetterGrades([95, 85, 71]);
In this case the main difference between forEach() and map() is that map() returns a NEW array (that's why you return values in the function body), and forEach() doesn't (we had to create the array - grade- manually, and push values into this "hand-made" array).
Look below to see what would happen, if we used forEach() WITHOUT a manually created array:
// THIS IS NOT A GOOD SOLUTION!
// IT GIVES YOU THE ANSWER IN THIS SMALL EXAMPLE
// (so you see that it's possible)
// BUT IN ANY LARGER CODE THIS IS THE
// 100% SURE SOURCE OF ERRORS.
let grades = []
function getLetterGrades(grades) {
grades.forEach((item, index) => {
if (item < 60) {
grades[index] = "F";
} else if (item < 70) {
grades[index] = "D";
} else if (item < 80) {
grades[index] = "C";
} else if (item < 90) {
grades[index] = "B";
} else if (item < 100) {
grades[index] = "A";
}
})
// console.log(grades) - NOT grade!
console.log(grades);
}
getLetterGrades([95, 85, 71]);
(I used the second argument of forEach() - that's index) THIS IS NOT A GOOD SOLUTION! Why? We "destroyed" our original grades array by overwriting it in getLetterGrades() - DON'T DO THIS!
As stated on map() takes a function and runs it once on each object in the array. To be clear on how you're trying to use it:
function getLetterGrades(grade) {
if (grade < 60) {
return "F";
} else if (grade < 70) {
return "D";
} else if (grade < 80) {
return "C";
} else if (grade < 90) {
return "B";
} else if (grade < 100) {
return "A";
}
}
x = [95, 85, 71];
//=> [A, B, C]
x.map(getLetterGrades);
Functionally, this is what the other answers are doing, they just aren't naming the method.
Post edited to change link as comment pointed out better resource.
Else condition is executed every time. If input is '11' answer is 'f' not 'D', I know the last condition should be else if but according to the logic of input is 11 output should be 'D'
function getGrade(score) {
let grade;
var score1 = Number(score);
// Write your code here
if (score1 > 25 && score <= 30)
grade = "A";
else if (score1 > 20 && score <= 25)
grade = "B";
else if (score1 > 15 && score <= 20)
grade = "C";
else if (score1 > 10 && score <= 15)
grade = "D";
else if (score1 > 5 && score <= 10)
grade = "E";
else (score1 > 0 && score <= 5)
grade = "F";
return grade;
}
Is it a copy-paste? Then it's a matter of typo.
else (score1 > 0 && score <= 5)
grade = "F";
if is missing here. Therefore, (score1 > 0 && score <= 5) is interpreted as the thing to do (so, evaluate an expression), and the next line is outside of any else/if branch and simply gets executed always.
You can use the parenthesis around the else if. Also for the last condition you can simple use else instead of else if
function getGrade(score) {
let grade;
var score1 = Number(score);
console.log(score1)
// Write your code here
if (score1 > 25 && score <= 30) {
grade = "A";
} else if (score1 > 20 && score <= 25) {
grade = "B";
} else if (score1 > 15 && score <= 20) {
grade = "C";
} else if (score1 > 10 && score <= 15) {
grade = "D";
} else if (score1 > 5 && score <= 10) {
grade = "E";
} else {
grade = "F";
}
return grade;
}
console.log(getGrade(11))
A better approach, is to use an early exit paradigm, starting with wrong values and then take a ladder of conditions which rely on the conditions before.
function getGrade(score) {
var score1 = Number(score);
if (isNaN(score1) || score1 > 30 || score1 < 0) return;
if (score1 > 25) return "A";
if (score1 > 20) return "B";
if (score1 > 15) return "C";
if (score1 > 10) return "D";
if (score1 > 5) return "E";
return "F";
}
I'm new to code so my mistake is probably obvious but,
When I go and test the calculator, it reads "A" then where ever the proper grade should be then Undefined. Idk where I'm going wrong.
I've tried a lot of different variations, and can't get the calculator to work properly. I'm not sure where the problem is.
function calculateGrade(grade) {if (parseInt >= "90"){
alert ("A");
}
else if (parseInt >= "80" === parseInt < "90"){
alert ("B");
}
else (parseInt >= "70" === parseInt < "80");{
alert ("C");
}
if (parseInt >= "60" === parseInt < "70"){
alert ("D");
}
else if (parseInt < "60"){
alert ("F");
}}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
Suggestions and errors in your code
You already have parsed into number, so leave the '90' quotes from the numbers.
Don't use magic names and global variables. Your function accepts the grade argument. Use it in your code.
Your if else conditions are wrong. Some of them are without else if. You can left the second part of each else if conditions.
Return the final which you expect from the function.
function calculateGrade(grade) {
let final = '';
if (grade >= 90) {
final = 'A';
} else if (grade >= 80) {
final = 'B';
} else if (grade >= 70) {
final = 'C';
} else if (grade >= 60) {
final = 'D';
} else {
final = 'F';
}
return final;
}
let inputGrade = prompt("Enter a grade:");
let parsedInt = Number.parseInt(inputGrade);
let finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
You could use a patttern with early exit and start frim the smallest value check to the greatest value.
The early exit returns a function and no more check is performed, because the function has ended with return statement.
For taking an integer value with parseInt, you should use a radix of 10, because without and with leading zero the number is treated as octal number, which you do not want.
A last advice, please do not use name of build in functions or objects or reserved words as variable names. This could lead to not proper working code and to searching without reason.
function calculateGrade(grade) {
if (grade < 50){
return "F";
}
if (grade < 60){
return "E";
}
if (grade < 70) {
return "D";
}
if (grade < 80) {
return "C";
}
if (grade < 90) {
return "B";
}
return "A";
}
var inputGrade = prompt("Enter a grade:"),
grade = parseInt(inputGrade, 10),
finalGrade = calculateGrade(grade);
console.log(finalGrade);
Try it
function calculateGrade(grade) {
if (grade < 60){
alert ("F");
}
else if (grade >= 60 && grade < 70){
alert ("D");
}
else if(grade >= 70 && grade < 80);{
alert ("C");
}
else if (grade >= 80 && grade < 90){
alert ("B");
}
else if (grade >= 90){
alert ("A");
}
}
var inputGrade = prompt("Enter a grade:");
var parsedInt = parseInt(inputGrade);
var finalGrade = calculateGrade(parsedInt);
alert(finalGrade);
I was trying to mess around javascript and I created a multidimensional kinda array:
var students = [ [['David'], [80]], [['Vinoth'], [77]], [['Goren'],[55]] ];
And then I created an if statements that will test if the student grade is F to A.
for (var i = 0; i < students.length; i++) {
for (var j = 1; j < students.length; j++) {
document.write(students[i][j] + "<br/>");
if (students[i][j] < 60) {
document.write(students[i][j] + " is Grade : F");
} else if (students[i][j] < 70) {
document.write(students[i][j] + " is Grade : D");
} else if (students[i][j] < 80) {
document.write(students[i][j] + " is Grade : C");
} else if (students[i][j] < 90) {
document.write(students[i][j] + " is Grade : B");
} else if (students[i][j] < 100) {
document.write(students[i][j] + " is Grade : A");
}
}
}
In my pursuit to output the name of the student and the grade I even end up creating three for loops which did not work.
I was wondering how can I achieve this output:
David's grade is 80 and is C Grade.
Vinoth's grade is 77 and is C Grade.
Goren's grade is 55 and is F Grade.
Any idea what's missing to my codes?
Other answers have suggested simplifying your array structure. If you really want to use your extra nesting, you need to do an extra level of indexing. But you don't need nested loops, because it's still just a linear structure.
for (var i = 0; i < students.length; i++) {
var student = students[i][0][0];
var score = students[i][1][0];
var grade;
if (score < 60) {
grade = "F";
} else if (score < 70) {
grade = "D";
} else if (score < 80) {
grade = "C";
} else if (score < 90) {
grade = "B";
} else if (score < 100) {
grade = "A";
}
document.write(student + "'s score is " + score + ' and is Grade ' + grade + '<br>');
}
Also, if you expect a score of 80 to generate a C grade rather than B, you should be using <= rather than < in the comparisons.
As a general rule, I recommend using objects rather than arrays for heterogeneous data, so your array should be like:
var students = [ {
name: 'David',
score: 80
}, {
name: 'Vinoth',
score: 77
}, {
name: 'Goren',
score: 55
}];
Then you use students[i].name and students[i].score, which is much easier to understand.
The idea is that you use arrays for collections of things that are all the same type, and objects for collections of related information about a thing.
Your data is structure is strange in that it is deeply nested.
I would transform it to the shallower:
var students = [ [ 'David', 80], ['Vinoth', 77], ['Goren', 55] ];
It would be better to define a single argument function for determining the grade letter:
function getGrade(value) {
if (value > 90) return 'A';
else if (value > 80) return 'B';
else if (value > 70) return 'C';
else if (value > 60) return 'D';
else return 'F'
}
I would prefer a forEach loop but since you seem to have a preference for the for, we can write:
for (let i = 0; i < students.length; i++) {
console.log(`${students[i][0]}'s grade is ${students[i][1]} and is a ${getGrade(students[i][1])} Grade`);
}
Your array is 3 level nested. So you might want to run 3 loops. However the second level has only 2 elements and the third level has only 1 element. So you can run only 1 loop. See the following working snippet.
var students = [ [['David'], [80]], [['Vinoth'], [77]], [['Goren'],[55]] ];
for (var i = 0; i < students.length; i++) {
document.write(students[i][0][0] + " ");
if (students[i][1][0] < 60) {
document.write(students[i][1][0] + " is Grade : F" + "<br/>");
} else if (students[i][1][0] < 70) {
document.write(students[i][1][0] + " is Grade : D"+ "<br/>");
} else if (students[i][1][0] < 80) {
document.write(students[i][1][0] + " is Grade : C"+ "<br/>");
} else if (students[i][1][0] < 90) {
document.write(students[i][1][0] + " is Grade : B"+ "<br/>");
} else if (students[i][1][0] < 100) {
document.write(students[i][1][0] + " is Grade : A"+ "<br/>");
}
}
If you really, REALLY want to just fix your solution with just the minimum modifications without touching your data, then you were missing 3 things to get the output you wanted:
document.write("<br>") at the end
inner loop until students.length - 1
name of stundent accessed as students[i][j - 1]
Here's the complete fixed code, run it by clicking "Run code snippet" at the bottom
var students = [ [['David'], [80]], [['Vinoth'], [77]], [['Goren'],[55]] ];
for (var i = 0; i < students.length; i++) {
for (var j = 1; j < students.length - 1; j++) {
document.write(students[i][j - 1] + "'s grade is ");
if (students[i][j] < 60) {
document.write(students[i][j] + " and is Grade : F");
} else if (students[i][j] < 70) {
document.write(students[i][j] + " and is Grade : D");
} else if (students[i][j] < 80) {
document.write(students[i][j] + " and is Grade : C");
} else if (students[i][j] < 90) {
document.write(students[i][j] + " and is Grade : B");
} else if (students[i][j] < 100) {
document.write(students[i][j] + " and is Grade : A");
}
}
document.write("<br>")
}
Your students array's inner elements such as name or grade are themselves wrapped in brackets and thus become arrays. Remove the inner brackets.
Also, your comparison operator < should become <= if you want a score of 80 to be rated as a 'C' as per your example.
let students = [['David', 80], ['Vinoth', 77], ['Goren', 55]];
// Define rating function:
let rate = (grade) => grade <= 60 ? 'F' : grade <= 70 ? 'D' : grade <= 80 ? 'C' : grade <= 90 ? 'B' : 'A';
// Map students to phrases:
let phrases = students.map((student) => `${student[0]}'s grade is ${student[1]} and is ${rate(student[1])} grade.`);
// Output DOM nodes:
phrases.forEach((phrase) => {
let el = document.createElement('div');
el.textContent = phrase;
document.body.appendChild(el);
});
Array of objects is a better data structure for this particular case. Plus I have separated the score to grade conversion to a function, which makes code easier to read and reason about.
function getGrade (score) {
var grades = [
{
letter: 'A',
minScore: 90
},
{
letter: 'B',
minScore: 80
},
{
letter: 'C',
minScore: 70
},
{
letter: 'D',
minScore: 60
},
{
letter: 'F',
minScore: 0
}
];
for (var i = 0; i < grades.length; i++) {
if (grades[i].minScore <= score) return grades[i].letter;
}
}
var students = [
{
name: 'David',
score: 80
},
{
name: 'Vinoth',
score: 77
},
{
name: 'Goren',
score: 55
}
];
students.forEach(function (student) {
var str = student.name +
"'s score is " +
student.score +
" and is " +
getGrade(student.score) +
" Grade.";
console.log(str);
});
I hope this will works for you
var students = [ [['David'], [80]], [['Vinoth'], [77]], [['Goren'],[55]] ];
for (var i = 0; i < students.length; i++) {
document.write("<br/>"+students[i][0] + "'s");
for (var j = 1; j < students.length; j++) {
console.log(students[i][0]);
if (students[i][j] < 60) {
document.write(students[i][j] + " is Grade : F");
}
else if (students[i][j] < 70) {
document.write(students[i][j] + " is Grade : D");
} else if (students[i][j] < 80) {
document.write(students[i][j] + " is Grade : C");
} else if (students[i][j] < 90) {
document.write(students[i][j] + " is Grade : B");
} else if (students[i][j] < 100) {
document.write(students[i][j] + " is Grade : A");
}
}
}
1. Create a function toLetterGrade that takes an array of percentages and returns an array of corresponding grade letters. For example:
toLetterGrade([90,80,55,85]); //returns ["A","A-","C","A"]
2. Create a function toGradePoints that takes an array of letter grades and returns a corresponding array of grades points. For example:
toGradePoints(["A","A-","C","A"]); //returns [4.0,3.7,2.0,4.0]
3. Create a function GPA that takes an array of percentages and returns the corresponding grade point average.
I'm trying to do number 1, and this is the code I have so far, but it only gives me the letter grade for the last number in the array. What am I doing wrong?
var arr
function toLetterGrade(arr) {
for (i = 0; i < arr.length; i++) {
if (arr[i] >= 85) {
textG = "A";
} else if (arr[i] >= 80) {
textG = "A-";
} else if (arr[i] >= 75) {
textG = "B+";
} else if (arr[i] >= 70) {
textG = "B";
} else if (arr[i] >= 65) {
textG = "B-";
} else if (arr[i] >= 60) {
textG = "C+";
} else if (arr[i] >= 55) {
textG = "C";
} else if (arr[i] >= 50) {
textG = "D";
} else {
textG = "F";
}
}
return textG;
}
document.write(toLetterGrade([90, 80, 70]))
Output is B.
You are overwriting your variable with every cycle of the loop, that's why you are getting only one - the last grade.
I suggest you to use an empty array variable to store results inside.
With every loop you will assign new grade to the textG variable and then push it into the result array. The textG variable gets reseted with every loop textG = '' so there's no risk to duplicate/overwrite results.
After all cycles of the for loop, the result array is returned.
function toLetterGrade(arr) {
var textG = '';
var result = [];
for (i = 0; i < arr.length; i++) {
textG = '';
if (arr[i] >= 85) {
textG = "A";
} else if (arr[i] >= 80) {
textG = "A-";
} else if (arr[i] >= 75) {
textG = "B+";
} else if (arr[i] >= 70) {
textG = "B";
} else if (arr[i] >= 65) {
textG = "B-";
} else if (arr[i] >= 60) {
textG = "C+";
} else if (arr[i] >= 55) {
textG = "C";
} else if (arr[i] >= 50) {
textG = "D";
} else {
textG = "F";
}
result.push(textG);
}
return result;
}
document.write(toLetterGrade([90, 80, 70]))
For the first part, you could use an object and iterate the keys for the wanted grade.
function getGrade(p) {
var grade = 'F';
Object.keys(grades).some(function (k) {
if (p >= grades[k]) {
grade = k;
return true;
}
});
return grade
}
var grades = { A: 85, 'A-': 80, B: 70, 'B-': 65, 'C+': 60, C: 55, D: 50, F: '' }
console.log([90, 80, 55, 85].map(getGrade));
.as-console-wrapper { max-height: 100% !important; top: 0; }
You're assigning the grade to a variable and then overwriting it with each iteration.
try textG.push('A') instead
You are overwriting your return value with each iteration.
Try creating an array, and adding the solution onto the array.
var solutionArr = [];
solutionArr.push("A");
jsfiddle
I make this simple code to check letter grade from a numerical
const letterGrade = (n) => {
let resultGrade = "";
if (n >= 90) {
resultGrade = "A";
} else if (n >= 80 || n > 89) {
resultGrade = "B";
} else if (n >= 70 || n > 79) {
resultGrade = "C";
} else if (n >= 60 || n > 69) {
resultGrade = "D";
} else if (n < 59) {
resultGrade = "E";
} else {
alert("Input your grade first");
}
return `Your grade is ${resultGrade}`;
};
console.log(letterGrade(75));