ignoring empty strings when looping through an array in JavaScript - javascript

I am attempting to go through an array and add up all the numbers. I used console.log to show me what values the script was using as shown below. I keep trying different variations of things in the if() but nothing seems to be working properly.
var billycount = 0;
var billyTotalScore = billyScoreList.reduce(function(score, total) {
if(score === " ") {
billycount += 1;
}
return +total + +score;
});
console.log(billycount); //0
console.log(billyTotalScore); //30
console.log(billyScoreList); // ["12", " ", "18"]
console.log(billyAverageScore) //10
var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);
The answer to billyAverageScore should equal 15 (30/2).
I tried if(score === "0") which gives me the same answers as above and if (score !== true) which gives me a count of 2 and an average of 30. I think reduce() is treating the empty string as a 0. I want to be able to count all the empty strings so I can discount them from the length when finding the average.
I have been wrestling this forever and feel like I'm missing one key concept behind it. Any help would be great! Thanks!
UPDATE:
For anyone who stumbles across this, here is the code I got to work.
var billycount = 0;
var billyTotalScore = billyScoreList.reduce(function(total, score) {
if (score === " " || total === " ") {
billycount++;
}
return +total + +score;
});
var billyAverageScore = billyTotalScore/(billyteamlist.length - billycount);
When I was just checking if (score === " ") I was forgetting that score will never be equal to the first term in the array. I just added || total === " ". the only time this would break down would be if the first element was " " and the second element was 0. I would want to billycount++ for the first element but not for the second. I'll have to give that some more thought.

The callback function of reduce should be function(total, score) instead of function(score, total).
see MDN:
previousValue
The value previously returned in the last invocation of the callback, or initialValue, if supplied. (See below.)
currentValue
The current element being processed in the array.

Related

A task in JavaScript

I need to create a sequence of numbers using while or for that consists of the sum of the symbols of the number.
For example, I have a sequence from 1 to 10. In console (if I've already written a code) will go just 1, 2,3,4,5,6,7,8,9,1. If I take it from 30 to 40 in the console would be 3,4,5,6,7,8,9,10,11,12,13.
I need to create a code that displays a sum that goes from 1 to 100. I don't know how to do it but in console I need to see:
1
2
3
4
5
5
6
7
8
9
1
2
3
4
etc.
I've got some code but I got only NaN. I don't know why. Could you explain this to me?
for (let i = '1'; i <= 99; i++) {
let a = Number(i[0]);
let b = Number(i[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log ('b false', a)
}
else {
console.log ('b true', a + b)
}
}
I hope you get what I was speaking about.
Although I like the accepted answer however from question I gather you were asking something else, that is;
30 become 3+0=3
31 become 3+1=4
37 becomes 3+7=10
Why are we checking for boolean is beyond the scope of the question
Here is simple snnipet does exactly what you ask for
for (let i = 30; i <= 40; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
what er are doing is exactly what Maskin stated begin with for loop then in each increment convert it to string so we can split it, this takes care of NAN issue.
you don't need to call to string just do it once as in let x then simply call the split as x[0] and so on.
within second number we have created a self computation (x[1])||0) that is if there is second value if not then zero. following would work like charm
for (let i = 1; i <= 10; i++) {
let x=i.toString();
console.log( 'numbers from ' +i + ' are added together to become '+ (Number(x[0])+Number((x[1])||0)))
}
Did you observe what happens to ten
here is my real question and solution what if you Don't know the length of the digits in number or for what ever reason you are to go about staring from 100 on wards. We need some form of AI into the code
for (let i = 110; i <= 120; i++) {
let x= Array.from(String(i), Number);
console.log(
x.reduce(function(a, b){ return a + b;})
);
};
You simply make an array with Array.from function then use simple Array.reduce function to run custom functions that adds up all the values as sum, finally run that in console.
Nice, simple and AI
You got NaN because of "i[0]". You need to add toString() call.
for (let i = '1'; i <= 99; i++) {
let a = Number(i.toString()[0]);
let b = Number(i.toString()[1])
let b1 = Boolean(b)
if (b1 == false) {
console.log('b false', a)
} else {
console.log('b true', a + b)
}
}
So the way a for loop works is that you declare a variable to loop, then state the loop condition and then you ask what happens at the end of the loop, normally you increment (which means take the variable and add one to it).
When you say let i = '1', what you're actually doing, is creating a new string, which when you ask for i[0], it gives you the first character in the string.
You should look up the modulo operator. You want to add the number of units, which you can get by dividing by 10 and then casting to an int, to the number in the tens, which you get with the modulo.
As an aside, when you ask a question on StackOverflow, you should ask in a way that means people who have similar questions to you can find their answers.

comparing array position to prompt (javascript)

I'm trying to compare the input from a prompt window to the position of the correct answer in an array within an array.
This function logs the question and possible answers to the console. It then logs the correct answer, but does not recognize the input as correct ie. it will always show the else statement.
Code:
questionArray[randomQ].questionPrompt();
var currentQ = randomQ;
Question.prototype.answerPrompt = function(){
var tryQ = prompt("Enter number of the correct answer.");
if (currentQ === tryQ){
console.log('The correct answer is ' + this.answer)
} else {
console.log('Try again. ' + this.answer)
}
};
Console log. The final line comes after input of 0:
Question?
0) answer 0 - correct answer
1) answer 1
2) answer 2
Try again. 0
If I use
if (questionArray.answerArray[currentQ] === tryQ)
then the correct array item is found, and listed as undefined in a TypeError. How do I use that array item to compare to the prompt answer?
prompt will always return a string, so it won't be === to a number. Cast the prompt result to a number first.
You also probably want to exclude the empty string from defaulting to 0.
const guess = prompt("Enter number of the correct answer.");
const tryQ = guess && Number(guess);

Javascript if else conditionals not returning the desired output [duplicate]

This question already has answers here:
if statement always return true even for simple integer values
(3 answers)
Closed 2 years ago.
I've been teaching myself how to code in new languages and might be asking a couple of silly questions here for a while.
Trying to put this to work but, when the output pops out and the grade I've typed into is higher than 50, it was supposed to show the word "PASS". Instead, I'm still getting "FAIL" - the amount doesn't matter.
I am pretty sure it has to do with the conditionals, but I've been stuck on this for a long time now.
Here is my code:
var input = Number(prompt("Enter a grade between 0 and 100.")); //enter grade
if (input > 100 || input < 0) {
alert("Grade not valid. Enter a grade between 0 and 100."); //validate grade
} else {
if (input < 50); //result FAIL
{
result = "Fail";
alert("FAIL");
}
/*
if (input > 50); //result PASS - This part doesn't work
{
result = "Pass";
alert("PASS");
}
*/
total = total + input;
entrys = entrys + 1; //show inputed grades
document.write("<br>" + "Grade " + entrys + " = " + input + " = " + input / 100 + "%" + " " + result); // Every inputed result is considered "Fail"
}
The semicolon after the if (input < 50) turns the if statement into a one line if with an empty expression, followed by a code block that always runs. You can fix your issue by getting rid of the semicolon.
if (input < 50); //result FAIL
// ^ this is bad
As others have already pointed out, you need to remove the ; from the line if you want the rest of the statements to execute. The reason why is because, traditionally, in compiler languages the semicolon(;) is used to mark the end of the line. In javascript, they are also used for that purpose, but they are optional in javascript.
So if your code spans multiple lines, avoid using it unnecessarily. Definitely don't use it after a for or while loop(unless for certain use cases where you want that), or after an if-else statement, because execution will get stopped at that line and the next line will be executed like it is an unrelated code and not part of the loop/statement. Hope this makes sense

JavaScript check if a random number has not been used already

I need to get random numbers but can't use the same number more than once.
I wrote the following functions to create a random number and to check if it has not been used yet.
function randomRecep(){
return Math.floor((Math.random() * 3));
}
function assignTemp(tempArr){
console.log("Started assign function, tempArr has: "+tempArr);
var num = randomRecep();
for (var i = 0; i < tempArr.length; i++) {
console.log("num is: " + num + ". check for doubles. tampArr["+i+"] is: "+tempArr[i]);
if (num == tempArr[i]){
console.log("FOUND DOUBLE! random num = "+num+" IS ALREADY IN array:"+tempArr)
assignTemp(tempArr);
break;
}
}
tempArr.push(num);
console.log("pushed " + num + "into array. now is:" + tempArr);
return num;
}
following is a console output. it seems that the check is working but for some reason at the end of the check instead of just pushing the unique random number and returning its value, it seems that the program pushes also all the previous duplicate numbers and returns the first random number instead of the last one that passed the check. why is that?
Started assign function, tempArr has: -1,2,1
code.js:104 num is: 1. check for doubles. tampArr[0] is: -1
code.js:104 num is: 1. check for doubles. tampArr[1] is: 2
code.js:104 num is: 1. check for doubles. tampArr[2] is: 1
code.js:106 FOUND DOUBLE! random num = 1 IS ALREADY IN array:-1,2,1
code.js:101 Started assign function, tempArr has: -1,2,1
code.js:104 num is: 1. check for doubles. tampArr[0] is: -1
code.js:104 num is: 1. check for doubles. tampArr[1] is: 2
code.js:104 num is: 1. check for doubles. tampArr[2] is: 1
code.js:106 FOUND DOUBLE! random num = 1 IS ALREADY IN array:-1,2,1
code.js:101 Started assign function, tempArr has: -1,2,1
code.js:104 num is: 0. check for doubles. tampArr[0] is: -1
code.js:104 num is: 0. check for doubles. tampArr[1] is: 2
code.js:104 num is: 0. check for doubles. tampArr[2] is: 1
code.js:113 pushed 0into array. now is:-1,2,1,0
this result is good and the idea is that it would stop here. but the process continues on:
code.js:113 pushed 1into array. now is:-1,2,1,0,1
code.js:113 pushed 1into array. now is:-1,2,1,0,1,1
I found code which is much simpler that achieves the above goal. However I am trying to learn and I don't yet understand what went wrong at the end of my method. where is the flaw in the logic?
So the problem with your current code is that you use break, where return should be used here
if (num == tempArr[i]){
console.log("FOUND DOUBLE! random num = "+num+" IS ALREADY IN array:"+tempArr)
assignTemp(tempArr);
break; // <-- should be return instead
}
The reason for this is, that once a non-unique number is found, you restart searching the next numbers, but the break will exit the loop, and directly after the for loop, you add num to your array. So, it would first add a potentially new unique number, and then exit that loop, and return to exit your first loop and then add the non-unique number ;)
You could also rewrite your code in the following way (I do not know if you have any requirements to a certain JavaScript versions, or you are only allowed to use a for loop)
function randomRecep(){
return Math.floor((Math.random() * 3));
}
function assignTemp(tempArr){
const number = randomRecep();
if (tempArr.includes( number ) ) {
console.warn( `${number} exists in [${tempArr.join(', ')}]` );
return assignTemp(tempArr);
}
console.warn( `adding ${number} to [${tempArr.join(', ')}]` );
tempArr.push( number );
return tempArr;
}
const output = [];
// shouldn't call this more than the nr of output possibilities (and the pool here has 3 options)
assignTemp( output );
assignTemp( output );
assignTemp( output );
// we will always expect 0, 1, 2 in the output in some manner
console.log( output );

Multiplying Integers on a For Loop

Beginning JavaScript learner here...
I'm working through Adrian Neumann's Simple Programming Problems and my question is about number 6 in the elementary exercises.
Write a program that asks the user for a number n and gives him the possibility to choose between computing the sum and computing the product of 1,…,n.
// var myArray = []; // for testing
var mySum = 0;
var userNum = prompt("What is your number? ");
var userChoice = prompt("Would you like to add up (+) or multiply (*) all the numbers from 1 to your number? Please enter (+) or (*): ");
if (userChoice == "+") {
for (var i = userNum; i > 0; i--) {
mySum += +i;
}
console.log("Your answer is " + mySum);
} else if (userChoice == "*") {
for (var i = userNum; i > 0; i--) {
mySum *= +i;
// myArray.push(i); // for testing
}
console.log("Your answer is " + mySum);
// console.log(myArray); // for testing
}
When entering values for multiplication, the answer is always 0. Obviously, I thought 0 was being included in the iteration, so I setup an empty array myArray, and pushed all the numbers to the array using myArray.push(i);... 0 was never included as a value in the array.
Other than some obvious form-validation considerations, can anyone tell me what I'm missing? Why is my answer always 0?
Note: The sum section of the code seems to work brilliantly.
Please note I'm a beginniner to JavaScript, so if you'd like to comment, let me know WHY you changed the code the way you do, rather than simply spitting back code to me. That's a big help, thanks.
Well, you initialize mySum to 0 so in every iteration of the loop you'll multiplying i by zero and save the result (again, zero) back into mySum. For multiplication you'd have to start at one.
You didn't set mySum to 1 before multiplication. 0*i = 0.

Categories

Resources