Trying to get values from different arrays to average them - javascript

I'm working on this assignment where basically I'm gathering data from users to input their student's grades. I was prompted to store the student names and 4 of each student's grades and average them out in the end. I have hit a hole and unsure how to get these values to add them up and average them.
Here's what I have written so far:
let lab1 = [];
let lab2 = [];
let lab3 = [];
let lab4 = [];
let stuName = [];
let grades = [];
let grade = 0;
let tGrade = 0;
do {
let tName = prompt("Enter Student Name: ");
stuName[stuName.length] = tName;
//prompting user for a grade and converting it LAB1
tGrade = prompt("Input Grade for lab 1: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
lab1[lab1.length] = grade;
}
//prompting user for a grade and converting it LAB2
tGrade = prompt("Input Grade for lab 2: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
lab2[lab2.length] = grade;
}
//prompting user for a grade and converting it LAB3
tGrade = prompt("Input Grade for lab 3: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
lab3[lab3.length] = grade;
}
//prompting user for a grade and converting it LAB4
tGrade = prompt("Input Grade for lab 4: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
lab4[lab4.length] = grade;
}
//giving user option to end inputs
tGrade = prompt("Do you want continue? -1 to exit: ", "-1");
grade = parseInt(tGrade);
} while (grade != -1); //loop escape

Here a solution storing the students with their grades in an object and storing this object in an array. This makes it a bit easier than having 5 different arrays like
let lab2 = [];
let lab3 = [];
let lab4 = [];
let stuName = [];
let grades = [];
To calculate the average you can go then over these objects and build the sum of the grades array and divide it by its length
objStore.forEach((x) => {
let sum = x.grades.reduce((acc, el) => {
acc += el;
return acc;
},0);
console.log(sum / x.grades.length)
})
const objStore = [];
let grade = 0;
let tGrade = 0;
let temp;
do {
temp = {};
let tName = prompt("Enter Student Name: ");
temp["name"] = tName;
temp["grades"] = [];
//prompting user for a grade and converting it LAB1
tGrade = prompt("Input Grade for lab 1: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
temp.grades.push(grade);
}
//prompting user for a grade and converting it LAB2
tGrade = prompt("Input Grade for lab 2: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
temp.grades.push(grade);
}
//prompting user for a grade and converting it LAB3
tGrade = prompt("Input Grade for lab 3: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
temp.grades.push(grade);
}
//prompting user for a grade and converting it LAB4
tGrade = prompt("Input Grade for lab 4: ");
grade = parseInt(tGrade);
//If grade is valid, then add it to the array
if (grade >= 0 && grade <= 100) {
//info stored in the array
temp.grades.push(grade);
}
//giving user option to end inputs
tGrade = prompt("Do you want continue? -1 to exit: ", "-1");
grade = parseInt(tGrade);
objStore.push(temp);
} while (grade != -1); //loop escape
console.log(objStore);
// here we can now calculate the average
objStore.forEach((x) => {
let sum = x.grades.reduce((acc, el) => {
acc += el;
return acc;
},0);
console.log(sum / x.grades.length)
})

I'm assuming you want the average of each student rather than the average of each lab. I've not provided a complete solution because I assume that you'd prefer to have a pointer from which you can figure out more of a solution.
You should be able to loop though the stuName array in such a way that you can use the index of each item in the stuName array to find the corresponding values in the labx arrays.
There are many ways to do this, but a for loop, Array.forEach or Array.map should allow you to do this. (For Array.forEach and Array.map) the callback's second argument is the current index of the item in the array.
Example usage of Array.forEach:
const students = ['Neera', 'Erik', 'Dolly'];
const student_score = [2, 5, 6];
students.forEach((name, index) => console.log('Name: ' + name + ' has score ' + student_score[index]));

Related

Finding the grade based on the best score

So my program wants the user to input the number of students and their scores. Based on the best score it will follow this grading scheme:
The score is > or = the best - 10 then the grade is A.
The score is > or = the best - 20 then the grade is B.
The score is > or = the best - 30 then the grade is C.
The score is > or = the best - 40 then the grade is D.
Anything else is an F
This is my code so far:
var readlineSync = require('readline-sync')
let scoreArray = []
let best = 0
students = readlineSync.question('Enter the number of students: ');
for (var x = 0; x < students; x++){
score = readlineSync.question('Enter Score: ')
scoreArray.push(score);
}
for (var i = 0; i < scoreArray.length; i++){
var data = scoreArray[i];
if(best < scoreArray[i]){
best = scoreArray[i];
}
if(scoreArray[i] >= (best-10)){
grade = 'A';
}else if(scoreArray[i] >= (best-20)){
grade = 'B';
}else if(scoreArray[i] >= (best-30)){
grade = 'C';
}else if(scoreArray[i] >= (best-40)){
grade = 'D';
}else {
grade = 'F';
}
console.log('Student ' + i + ' score is ' + scoreArray[i] +' and grade is ' + grade);
}
When I run the code it sometimes displays the correct grade and sometimes it doesn't. It should display this:
Enter the number of students: 4
Enter Score: 40
Enter Score: 55
Enter Score: 70
Enter Score: 58
Student 0 score is 40 and grade is C. Student 1 score is 55 and grade
is B. Student 2 score is 70 and grade is A. Student 3 score is 58 and
grade is B.
Instead it displays the grades A,A,A,B.
It looks like you're iterating over scoreArray and updating best along the way. You should first get the max score from scoreArray so you know the best to start with, and then iterate over scoreArray. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max for more info, but put var best = Math.max(...scoreArray); before your for loop, and then your conditional logic should work.
scoreArray = [49, 81, 72, 80, 81, 36, 58];
var best = Math.max(...scoreArray);
for (var i = 0; i < scoreArray.length; i++) {
var data = scoreArray[i];
if (scoreArray[i] >= (best - 10)) {
grade = 'A';
} else if (scoreArray[i] >= (best - 20)) {
grade = 'B';
} else if (scoreArray[i] >= (best - 30)) {
grade = 'C';
} else if (scoreArray[i] >= (best - 40)) {
grade = 'D';
} else {
grade = 'F';
}
console.log('Student ' + i + ' score is ' + scoreArray[i] + ' and grade is ' + grade);
}

How to swap first and last digits of a number using for loop in Javascript

I need to ask user to input a 3 digit number and then swap the first and last numbers using a for loop. This is what I have so far, but I'm stuck. Using a for loop seems illogical, but that is what I have to do:
num = prompt("Please input a number with 3 digits.");
let firstDigit = num[0];
let secondDigit = num[1];
let lastDigit = num[2];
for (firstDigit < 10; secondDigit < 10; lastDigit < 10); {
console.log(lastDigit + secondDigit + firstDigit);
}
Please help!
Thanks
is it help for you?
// let num = prompt("Please input a number with 3 digits.");
// if (num.length > 3) alert("3 digits please");
// else {
// let answer = "";
// for (var i = 2; i >= 0; i--) {
// answer = answer + num[i];
// }
// console.log(answer);
//}
let num = prompt("Please input a number");
let temp = "";
let answer = "";
for(let i = 0 ; i < num.length; i++) {
if (i === 0) temp = num[i]; // save first number to temp
else if (i === num.length - 1) {
// When the last number is encountered, the last number is put at the beginning, and the first number stored in temp is put at the end.
answer = answer + temp;
answer = num[i] + answer;
}
else answer = answer + num[i];
}
console.log(answer);

Beginner - While Loop sum all user inputs under 50 - Javascript

I am still a beginner on Javascript and I have a question.
I would like to sum all user inputs under 50 if written 0 to stop the program and display their amount
By example:
First Number 5, Second number 3, Third Number 55, Fourth Number 0. (The program will print 8)
var userInput = parseInt(prompt('Write Number'));
while(userInput!=0) {
var userInput = parseInt(prompt('Try Again!'));
if(userInput < 50){
var sum = userInput + userInput;
}
document.write(sum + '<br>');
}
Thanks a lot
loop and add previous value if condition match :
var inputData = Number(prompt("Enter the input number"));
var finalOutput=0;
while (inputData > 0) {
if (!(inputData > 50)) {
finalOutput += inputData;
}
inputData = Number(prompt("Enter the input number"));
}
document.write("SUM is : " + finalOutput);
You'd do this:
var input = Number(prompt("Enter a number"));
var output = 0;
while (input > 0) {
if (!(input > 50)) {
output += input;
}
input = Number(prompt("Enter a number"));
}
document.write("The sum of all the numbers lower than 50 was " + output);

Javascript find average from user's input

I know there are similar questions on here to mine but I don't see the answer there.
Where am I going wrong with this JS code to find the average number from the user's input?
I want to keep entering numbers until -1 is entered. I think -1 is being counted as an input/
var count = 0;
var input;
var sum = 0;
while(input != -1){
input = parseInt(prompt("Enter a number"));
count++;
sum = sum + input;
sum = parseInt(sum);
average = parseFloat(sum/count);
}
alert("Average number is " + average);
This is the right order (without all the unnecessary parsing...)
var count = 0;
var input;
var sum = 0;
input = parseInt(prompt("Enter a number"));
while (input != -1) {
count++;
sum += input;
average = sum / count;
input = parseInt(prompt("Enter a number"));
}
alert("Average number is " + average);
DEMO
Note that you can calculate the average once outside of the loop and save some CPU.
You need to check after you take the input from the user.
while(input != -1){
input = parseInt(prompt("Enter a number"));
//The user enters -1 but still inside the while loop.
if(input != -1)
{
count++;
sum = sum + input;
}
sum = parseInt(sum);
average = parseFloat(sum/count);
}
Here is the function code you need.
var count = 0;
var input;
var sum = 0;
while(true){
input = parseInt(prompt("Enter a number"));
if(input != -1)
{
count++;
sum = sum + input;
sum = parseInt(sum);
}
else
break;
}
average = parseFloat(sum/count);
alert("Average number is " + average);
This will grab the average...Simply accumulate the values and then divide the total 'sum' by the number of 'inputs made'(in our case we just use the count++)
var count = 0;
var input;
var sum = 0;
while(input != -1){
count++;
input = prompt("Enter a number");
sum += input;
sum = parseInt(sum);
}
average = (sum/count);
alert("Average number is " + average);

Check meter from array of objects

I have an array of objects like this
var json = [{"price":"30.00","meter":"70"},{"price":"20.00","meter":"130"},{"price":"10.00","meter":"170"}];
How to check qty between this and calculate price. I wrote loop but its not working properly.
var mQty = 2.52;
var jCnt = json.length;
//alert(jCnt);
for (var j = 0; j < jCnt - 1; j++) {
nextj = j + 1;
//alert(nextj;
first = json[j].meter;
if (json[nextj].meter != '') {
second = json[nextj].meter - 1;
} else {
second = '';
}
if (mQty >= first && mQty <= second) {
//bettween meter from json obj
alert('if condition');
alert(json[j].price);
} else {
//under 70 meter
alert('else condition');
alert('40.00');
}
}
I think I understand the problem now. Your prices are per meter prices (I guess) and the more meters of something are ordered, the cheaper the price per meter. You want to find the matching price for a given length.
Since your prices are sorted in ascending order, the logic is pretty simple:
If the quantity/length is less than the required quantity/length of the first entry, use the default price.
Else use the price of the last element that has an equal or smaller quantity/length.
Example:
var price;
if (qty < prices[0].meter) {
price = defaultPrice;
}
else {
for (var i = 1; i <= prices.length; i++) {
price = prices[i - 1].price;
if (prices[i] && prices[i].meter > qty) {
break;
}
}
}
If you add the default price as first element to the array:
var prices = [{price: defaultPrice, meter: 0}, ...];
then you can omit the whole if...else statement:
var price;
for (var i = 1; i <= prices.length; i++) {
price = prices[i - 1].price;
if (prices[i] && prices[i].meter > qty) {
break;
}
}

Categories

Resources