I am pretty new to Javascript and I am struggling with one of my assignments.
This is the context:
Manipulate this data
var grades = "jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27";
Create an HTML page with inline JavaScript code that displays student data in a more readable format like so:
Name1 - score1
Name2 - score2
Your program should:
display each student name and score
capitalize the first letter of student name
display the total # of students,
display the lowest, highest, and average scores
Now, I was able to print the names and grades in a more readable format but I don't know how to go about capitalizing the first letter of each name and how to output the lowest, highest and average grades.
Here is my code:
<body>
<p id="demo"></p>
<script>
var grades =
"jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27";
let result = grades.split(", ");
function getNameAndGrade(Str) {
for (let i in result) {
document.write(
` <b>Name: </b>${result[i].slice(
0,
result[i].indexOf("|")
)} <b>Grade: </b>${result[i].slice(-2)} <br>`
);
}
}
getNameAndGrade(grades);
</script>
</body>
CodePudding user response:
Here's one way you could capitalize the first letter of each name and output the lowest, highest, and average grades:
<body>
<p id="demo"></p>
<script>
var grades = "jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27";
let result = grades.split(", ");
let scores = [];
let names = [];
for (let i in result) {
let name = result[i].slice(0, result[i].indexOf("|"));
names.push(name.charAt(0).toUpperCase() name.slice(1));
scores.push(parseInt(result[i].slice(-2)));
}
// Capitalize first letter of name
for (let i in names) {
document.write(`<b>Name: </b>${names[i]} `);
}
// Display the lowest, highest, and average scores
let lowest = Math.min(...scores);
let highest = Math.max(...scores);
let average = (scores.reduce((a, b) => a b, 0)) / scores.length;
document.write(`<br><b>Lowest: </b>${lowest}`);
document.write(`<br><b>Highest: </b>${highest}`);
document.write(`<br><b>Average: </b>${average}`);
document.write(`<br><b>Total: </b>${scores.length}`);
</script>
</body>
In this updated code, I first used two arrays to store the names and scores separately. Then I used a for loop to iterate through the names array and capitalize the first letter of each name using the charAt(0).toUpperCase()
method, and I used the Array.prototype.push()
method to add the capitalized names to the names array.
And I used another for loop to iterate through the scores array and used the Math.min()
and Math.max()
method to find the lowest and highest scores, and then I used scores.reduce()
method to find the average score. And I also used the scores.length
to find the total number of students.
CodePudding user response:
You need some refactoring.
First of all, don't let your function write directly to the DOM. Instead, make it return your desired data and prefer modular structure (functions are small and do only one tiny specific task)
function getNameAndGrade(couple) {
return {
name: couple.split('|')[0],
score: couple.split('|')[1]
}
}
To capitalize the first letter, get it with substring
method (0 is the position of the substring and 1 is a substring length) and then capitalize it with capitalize
. After that, add the rest of your string with substring(1)
(1 means here without 1 first letter).
function capitalizeFirstLetter(string) {
string.substring(0, 1).toUpperCase() string.substring(1)
}
It is a good practise to separate your logic and view. This means, one function for calculations and another one for writing it to the screen. It helps you reuse your code.
function displayCouples(couples) {
const displayData = couples.map(couple =>
`<b>${capitalizeFirstLetter(couple.name)}</b>: ${couple.score}`
)
document.getElementById('demo').innerHTML = displayData
}
To get min, max and average score, we use method map
. The only thing it is doing is putting the score instead of the whole name and score object into our math functions. It tells javascript to take the score field and not the whole object.
function getAverageScore(couples) {
return Math.sum(...pairs.map(couple => couple.score)) / couples.length
}
function getMaxScore(couples) {
return Math.max(...couples.map(couple => couple.score))
}
function getMinScore(couples) {
return Math.min(...couples.map(couple => couple.score))
}
And here all the work:
const input = "jim|25, sue|32, mary|34, ann|22, ted|28, frank|15, lisa|19, mike|30, ahn|26, vishaya|27"
// we use hetNameAndGrade inside map function. It means, we apply this function to every pair of name and score
const pairs = input.split(', ').map(getNameAndGrade)
displayCouples(pairs)
const min = getMaxScore(pairs)
const max = getMaxScore(pairs)
const average = getAverageScore(pairs)
CodePudding user response:
For capitalizing words, you can use a mixture of three functions: charAt()
, toUpperCase()
and slice()
.
The charAt()
function returns the character at a given position in a string.
Example:
const str = 'javascript';
const str2 = str.charAt(0);
console.log(str2);
//Output: j
The toUpperCase()
function converts all the characters of an input string to uppercase.
Example:
const str = 'javascript';
const str2 = str.toUpperCase();
console.log(str2);
//Output: JAVASCRIPT
Now, everything is capitalized. We, however need only the first letters to be capitalized. To capitalize the first character of a string, we can use the charAt()
to separate the first character and then use the toUpperCase()
function to capitalize it. Now, we would get the remaining characters of the string using the slice()
function.
The slice()
function slices a given string from a specified “start” position until the specified “end” position.
Example:
const str = 'javascript';
const str2 = str.slice(1);
console.log(str2);
//Output: avascript
So, we'll use all three of those to capitalize the first letters.
const str = 'javascript';
const str2 = str.charAt(0).toUpperCase() str.slice(1);
console.log(str2);
//Output: Javascript