Help with comparing to array values in JavaScript - javascript

I have developed this code with help from you guys here on stackoverflow. I have added an extra part to it where it compares two numbers from two different arrays, in this case offhire1 and pro2.
The problem is in my code where I have:
(offhire1[i].value > pro2[i].value)
It only allows me to contine if the numbers match i.e 100=100. But what I'm after is identifing any numbers that are greater than the value only 120 > 100. I have tested if the values are being passed and they are.
What is my mistake here can anyone suss it out.
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]+(([\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
var accumulator = 0;
var num2 = num1.value;
var i=0;
var offhire1 = [];
var pro2 =[];
for(var i = 0; i < num2; i++) {
offhire1[i] = document.getElementById('offhire1' + i);
pro2[i] = document.getElementById('pro2' + i);
var offhire2 = offhire1[i].value;
// var pro3 = pro2[i].value;
if(!offhire2.match(test2Regex)){
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
else if (offhire1[i].value > pro2[i].value) {
alert("You entered: " + pro2[i].value)
inlineMsg('offhire1' + i,'You have off hired to many items',10);
return false;
}
else{
accumulator += parseInt(offhire2);
}
}
if(accumulator <= 0){
inlineMsg('num1' ,'You have not off Hired any items',10);
return false;
}
return true;
}

I'm not quite sure I follow you. If the numbers are the same, the statement won't match.
One issue in your code is that you're comparing strings, not numbers. You may want to change it to:
(parseInt(offhire1[i].value) > parseInt(pro2[i].value))

Related

Luhn Check Javascript

I am attempting to have someone input there credit card number and validate if it is a valid number by doing the Luhn Check. I want to be able to check it if they input the whole card number as one big string or if they put spaces in it. In my function validate though I keep getting an error message that there is an illegal return statement for my total variable. Here is my current code.
<script type="text/javascript">
function validate(numbers) {
var sum;
var sum1;
var total;
for (i = 0; i < numbers.length; i++) {
if (numbers.length % 2 == 0) {
sum += numbers[i];
}
else
if ((numbers[i] * 2) >= 10) {
sum1 += numbers[i] - 9;
}
else
sum1 += numbers[i];
}
total = sum + sum1;
return total;
}
function cardnumber() {
var cardnumber = document.getElementById("input").value;
var numbers = cardnumber.split(" ");
var out = "";
for (i = 0; i < numbers.length; i++) {
out += validate(numbers[i]);
if (out % 10 == 0)
return true;
}
}
function getOutput() {
if (cardnumber()) {
alert("You card is valid.");
}
}
</script>
<body>
<h1>I will validate a credit card number</h1>
Card Type:
<input type="radio" id="c1" value="Visa">Visa</input>
Card number: <textarea id="input" style="vertical-align: middle;"></textarea></br>
<input type="button" value="Submit" onclick="getOutput()" /></br></br>
</body>
Your function validate is missing an opening curly brace after the for loop. This made your return statement outside of your function and since a return statement is invalid outside of a function it was an invalid return statement.
function validate(numbers){
var sum;
var sum1;
var total;
for (i=0; i<numbers.length; i++) { // this previous curly brace `{` was missing
if (numbers.length%2==0){
sum += numbers[i];
}
else
if ((numbers[i]*2)>=10){
sum1 += numbers[i] -9;
}
else
sum1 +=numbers[i];
}
total = sum + sum1;
return total;
}
EDIT WITH MORE CORRECTIONS:
There is quite a bit more wrong with the formatting of you functions you also need to include opening and closing curly braces around your other else statements. I would suggest getting a code editor like VS Code and downloading an extension similar to Bracket pair colorizer 2. It will highlight paired brackets together. This will help you with your formatting.
function validate(numbers){
var sum;
var sum1;
var total;
for (i=0; i<numbers.length; i++) {
if (numbers.length%2==0){
sum += numbers[i];
}
else {
if ((numbers[i] * 2) >= 10) {
sum1 += numbers[i] - 9;
}
else {
sum1 += numbers[i];
}
}
}
total = sum + sum1;
return total;
}
function cardnumber(){
var cardnumber= document.getElementById("input").value;
var numbers = cardnumber.split(" ");
var out ="";
for (i = 0; i < numbers.length; i++) {
out += validate(numbers[i]);
}
if (out %10==0)
return true;
}
function getOutput() {
if (cardnumber()) {
alert("You card is valid.");
}
}
These are all the changed lines (the left is new code and the right side is the old code):
Tips for completion
validate function
So, currently if you console.log your numbers are strings when they pass into the validate function. This is fine when they are sent into validate, but when you add the numbers at index i (i.e. numbers[i]) you should use parseInt(numbers[i], 10) to turn them into numbers, so for example sum += parseInt(numbers[i], 10); the same applies when adding to sum1. The other thing to note is that saying var sum will make sum equal the undefined value. When you add a number or string to an undefined value some unexpected things will probably happen, so since you need your sums and totals to be numbers you should instead initialize your sums and totals at 0. Like so:
var sum = 0;
var sum1 = 0;
var total = 0;
The only other thing wrong with your validate function is that your are checking if numbers.length%2==0 which instead you should be checking if i%2==0. You may have to think about why for a moment, but one thing you may notice is the length of numbers never changes during the iteration of the loop where as i does change at each step.
cardnumber function
Your out variable needs to be initialized to zero. Your cardnumber can instead be split by spaces and then joined by the empty string. This handles if the user accidentally types multiple spaces. Then since you join your split array you no longer would need a for loop.
var numbers = cardnumber.split(" ").join('');
var out =0;
out += validate(numbers);
Lines that need changing somehow
Here's a difference of the lines of the old code that where incorrect and need to be changed somehow. I'm not giving you the completed code, but hopefully this will be sufficient to help you figure out the rest on your own (I feel I shouldn't give you all of the solution due to some degree of academic integrity. I would feel I robbed you the opportunity to learn more if I don't at least let you think through and type it out on your own.). If you are wondering what needs to be changed on a specific line that is highlighted red all of it should be above, so best of luck.

convert array.push.(prompt()) into a number

when i run the program the browser tell me moy is NaN yet I took care to use .map(Number) to convert the array into a number . I need some help please.
var score = [];
var i = 0;
var choice = 0;
while(choice != null){
i++;
score.push(prompt("put the score number "+i));
score = score.map(Number);
choice = prompt("to continue click on ok to cancel click on cancel");
}
var sum = 0,moy;
for(a=0;a<=i;a++) {
sum = sum+score[a];
moy = sum/i;
}
document.write("you put "+i+" score(s) <br>and the average is"+moy);
you have syntax error in this line
for(a=0;a<=i;a++) {
define a variable like this
for(var a=0;a<=i;a++)

for loop not executing properly Javascript

i m trying to calculate weight of a string using the following function
function weight(w)
{
Cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
small = 'abcdefghijklmnopqrstuvwxyz'
spcl = "~!##$%^&*()_+[]\{}|;':,./<>?"
num = '0123456789'
var p = []
for(i=0;i<w.length;i++)
{
if(Cap.contains(w[i])==true)
p[i] = Cap.indexOf(w[i]) + 2
else if(small.contains(w[i])==true)
p[i] = small.indexOf(w[i]) + 1
else if(num.contains(w[i]))
p[i] = num.indexOf(w[i])
else if(spcl.contains(w[i]))
p[i] = 1
}
return _.reduce(p,function(memo, num){ return memo + num; }, 0);
}
where w is a string. this properly calculates weight of the string.
But whn i try to to calculate weight of strings given in a an array, it jst calculates the weight of the first element, ie. it does not run the full for loop. can anyone explain to me why is that so??
the for loop is as given below
function weightList(l)
{
weigh = []
for(i=0;i<l.length;i++)
weigh.push(weight(l[i]));
return weigh;
}
input and output:
>>> q = ['abad','rewfd']
["abad", "rewfd"]
>>> weightList(q)
[8]
whereas the output array should have had 2 entries.
[8,56]
i do not want to use Jquery. i want to use Vanilla only.
Because i is a global variable. So when it goes into the function weight it sets the value of i greater than the lenght of l. Use var, it is not optional.
for(var i=0;i<l.length;i++)
and
for(var i=0;i<w.length;i++)
You should be using var with the other variables in the function and you should be using semicolons.
I think your issue is just malformed JavaScript. Keep in mind that JavaScript sucks, and is not as forgiving as some other languages are.
Just by adding a few "var" and semicolons, I was able to get it to work with what you had.
http://jsfiddle.net/3D5Br/
function weight(w) {
var Cap = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ',
small = 'abcdefghijklmnopqrstuvwxyz',
spcl = "~!##$%^&*()_+[]\{}|;':,./<>?",
num = '0123456789',
p = [];
for(var i=0;i<w.length;i++){
if(Cap.contains(w[i])==true)
p[i] = Cap.indexOf(w[i]) + 2
else if(small.contains(w[i])==true)
p[i] = small.indexOf(w[i]) + 1
else if(num.contains(w[i]))
p[i] = num.indexOf(w[i])
else if(spcl.contains(w[i]))
p[i] = 1
}
return _.reduce(p,function(memo, num){ return memo + num; }, 0);
}
function weightList(l) {
var weigh = [];
for(var i=0;i<l.length;i++)
weigh.push(weight(l[i]));
return weigh;
}
q = ['abad','rewfd'];
results = weightList(q);
Hope that helps

Javascript: Example of recursive function using for loops and substring - can't figure out where I'm going wrong

I'm currently working on coderbyte's medium challenge entitled "Permutation Step."
The goal is to take user input, num, and to return the next number greater than num using the same digits So, for example, if user input is 123, then the number 132 should be returned. If user input is 12453, then 12534 should be returned...
Anywho, I have a correct model answer created by someone (probably a genius, cuz this stuff is pretty hard) and I'm trying to figure out how the answer works, line for line by having an example play out (I'm keeping it simple and playing out the function with user input 123).
The answer has 2 functions, but the 1st function used is what I'm currently trying to work out...
The relevant code is:
var PermutationStep1 = function(num) {
var num1 = num.toString();
var ar = [];
//return num1;
if (num1.length < 2) {
return num;
} else {
for(var i = 0; i < num1.length; i++) {
var num2 = num1[i];
var num3 = num1.substr(0,i) + num1.substr(i+1, num1.length -1);
var numAr = PermutationStep1(num3);
for(var j = 0; j < numAr.length; j++) {
ar.push(numAr[j] + num2);
}
}
ar.sort(function(a,b) {return a-b});
return ar;
}
}
Again, I'm trying to work thru this function with the inputted num as 123 (num = 123).
I'm pretty sure that this function should output an array with multiple elements, because the 2nd function merely compares those array elements with the original user input (in our case, 123), and returns the next greatest value.
So in our case, we should probably get an array, named 'ar', returned with a host of 3 digit values. But for some reason, I'm getting an array of 2 digit values. I can't seem to isolate my mistake and where I'm going wrong. Any help with where, specifically, I'm going wrong (whether it be the recursion, the use of substring-method, or the concating of strings together, whatever my problem may be) would be appreciated...
Here's some of my work so far:
PS1(123) / num1 = 123
i = 0;
num2 = (num1[i]) = '1';
num3 = (num1.substr(0, 0) + num1.substr(1, 2)) = ('0' + '23') = '23'
PS1(23)
i = 0;
num2 = '2';
num3 = '3'
PS1(3) -> numAr = 3 (since num1 is less than 2 digits, which is the recursion base case?)
(So take 3 into the 2nd for loop)...
ar.push(numAr[j] + num2) = ar.push('3' + '1') = 31
ar = [31] at this point
And then I go through the initial for-loop a couple more times, where i = 1 and then i = 2, and I eventually get....
ar = [31, 32, 33]...
But I'm thinking I should have something like ar = [131, 132, 133]? I'm not sure where I'm going wrong so please help. Because the answer is correctly spit out by this function, the correct answer being 132.
Note: if you need the 2nd part of the model answer (i.e. the 2nd function), here it is:
var arr = [];
function PermutationStep(num1) {
arr.push(PermutationStep1(num1));
var arrStr = arr.toString();
var arrStrSpl = arrStr.split(",");
//return arrStrSpl;
for(var p = 0; p < arrStrSpl.length; p++) {
if(arrStrSpl[p] > num1) {
return arrStrSpl[p];
}
}
return -1;
}
I'm sorry the first function i posted was under a mathematical logical mistake and i was to overhasty
I thought about it again and now i have the following function which definitley works
function getNextNumber (num)
{
var numberStr=num.toString (), l=numberStr.length, i;
var digits=new Array (), lighterDigits, digitAtWeight;
var weight,lightWeight, lighterDigits_l, value=0;
for (i=l-1;i>-1;i--)
digits.push (parseInt(numberStr.charAt(i)));
lighterDigits=new Array ();
lighterDigits.push (digits[0]);
for (weight=1;weight<l;weight++)
{
digitAtWeight=digits[weight];
lighterDigits_l=lighterDigits.length;
for (lightWeight=0;lightWeight<lighterDigits_l;lightWeight++)
{
if (digitAtWeight<lighterDigits[lightWeight])
{
lighterDigits.unshift (lighterDigits.splice (lightWeight,1,digitAtWeight)[0]);
lighterDigits.reverse ();
digits=lighterDigits.concat (digits.slice (weight+1,l));
for (weight=0;weight>l;weight++)
value+=Math.pow (10,weight)*digits[weight];
return value;
}
}
lighterDigits.push (digitAtWeight);
}
return NaN;
}
okay here is my solution i found it in 20 minutes ;)
//---- num should be a Number Object and not a String
function getNextNumber (num)
{
var numberStr=num.toString (), l=numberStr.length, i;
var digits=new Array (), digitA, digitB;
var weight,lightWeight;
var valueDifference,biggerValue;
for (i=l-1;i>-1;i--)
digits.push (parseInt(numberStr.charAt(i))); // 345 becomes a0=5 a1=4 a2=3 and we can say that num= a0*10^0+ a1*10^1+ a2*10^2, so the index becomes the decimal weight
for (weight=1;weight<l;weight++)
{
digitA=digits[weight];
biggerValue=new Array ();
for (lightWeight=weight-1;lightWeight>-1;lightWeight--)
{
digitB=digits[lightWeight];
if (digitB==digitA) continue;
valueDifference=(digitA-digitB)*(-Math.pow(10,weight)+Math.pow (10,lightWeight));
if (valueDifference>0) biggerValue.push(valueDifference);
}
if (biggerValue.length>0)
{
biggerValue.sort();
return (biggerValue[0]+num);
}
}
}
this is the solution I figured out for the problem without using a recursive function. It's passed all the tests on coderbyte. I am still new to this so using recursion is not the first thing I look for. hope this can help anyone else looking for a solution.
function PermutationStep(num) {
var numArr = (num + '').split('').sort().reverse();
var numJoin = numArr.join('');
for (var i = (num + 1); i <= parseInt(numJoin); i++){
var aaa = (i + '').split('').sort().reverse();
if (aaa.join('') == numJoin){
return i;
}
}
return -1;
}

Validation for numeric data Javascript

I'm writing a program in Javascript that separates even and odd numbers, puts them into an array, adds the sum of numbers, and finds the average.
I'm having an issue not allowing zeros not to count. Because its adding to the array, and when the user types in 6+6, sum is 12, average is calculating to 4 because of the extra 0 in the array.
Is there anyway to not allow the zeros to count? Here is what I have so far..
var evenarray = [];
var oddarray = [];
var avgEven = 0;
var avgOdd = 0;
var isValid;
function numberFunction(){
do
{
var numbers = prompt("Please enter numbers. Enter empty string to exit.");
if(numbers % 2 == 0)
{
evenarray.push(numbers);
var sumEven = 0;
for (var i=0; i < evenarray.length; i++)
{
sumEven = sumEven + Number(evenarray[i]);
}
var avgEven = sumEven/evenarray.length;
//alert("even");
}
if(numbers % 2 !== 0)
{
oddarray.push(numbers);
var sumOdd = 0;
for (var i=0; i < oddarray.length; i++)
{
sumOdd = sumOdd + Number(oddarray[i]);
}
var avgOdd = sumOdd/oddarray.length;
//alert("odd");
}
//if(isNaN(numbers)){
//alert("Only numeric data only");
//}
}
while(numbers !== "");
Just do nothing when the number is actually 0:
if (numbers == 0)
{
}
else if(numbers % 2 == 0)
{
evenarray.push(numbers);
var sumEven = 0;
for (var i=0; i < evenarray.length; i++)
{
sumEven = sumEven + Number(evenarray[i]);
}
var avgEven = sumEven/evenarray.length;
}
else // only odds remain
{
oddarray.push(numbers);
var sumOdd = 0;
for (var i=0; i < oddarray.length; i++)
{
sumOdd = sumOdd + Number(oddarray[i]);
}
var avgOdd = sumOdd/oddarray.length;
}
You can do :
if(numbers % 2 == 0 && numbers !=0) ...
if(numbers % 2 != 0 && numbers !=0) ...
so that you don't do anything when numbers == 0;
It's a little strange to call your variable numbers instead of number.
your function should be,
function numberFunction(){
do
{
var numbers = prompt("Please enter numbers. Enter empty string to exit.");
if(numbers !=0 && !isNaN(numbers))
(numbers %2 == 0)? (evenarray.push(parseInt(numbers))) : (oddarray.push(parseInt(numbers)));
}while(numbers !== "");
for(var i = 0; i < evenarray.length; i++)
sumEven += evenarray[i];
for(var i = 0; i < oddarray.length; i++)
sumOdd += oddarray[i];
avgEven = sumEven / evenarray.length;
avgOdd = sumOdd / oddarray.length;
document.getElementById("even").innerHTML = evenarray.toString();
document.getElementById("sumEvenTotal").innerHTML = sumEven.toString(); //displays sum of even numbers.
document.getElementById("averageOdd").innerHTML = avgOdd; //displays average of odd numbers.
document.getElementById("averageEven").innerHTML = avgEven; //diplays average of even numbers.
document.getElementById("odd").innerHTML = oddarray.toString(); //displays all odd numbers that were entered.
document.getElementById("sumOddTotal").innerHTML = sumOdd.toString();
}
As you already have other answers with solutions to your particular issue, I would suggest a different approach. Think of the data you're manipulating: an array. Try to solve the issue only with data, no user input, no DOM manipulation; just data. This helps to separate concerns, and make your code easier to understand.
Since we're working with arrays, we can make use of some of the built-in JavaScript methods that are present in modern browsers, such as filter and reduce. These methods are in a way, alternatives to for loops, with some pre-defined behavior, and a callback function.
Now, let's think of the steps involved in solving your problem.
Get numbers from the user. We can represent this data as an array, as you were already doing.
We want all odd numbers, their sum and average.
We want all even numbers, their sum and average.
We display the data to the user.
In this solution I'm assuming you already have an array with the data, and will be focusing on points 2 and 3. Remember, think of data, user interaction shouldn't be mixed with your data logic. Instead of asking the user for a number on each loop, you could ask the user for a list of numbers directly; you avoid multiple prompts this way, and it lets you separate data and interaction nicely. Ideally you'd validate all user input to match your requirements.
// Helpers to work with numbers
var odd = function(x) {
return x % 2 === 0;
};
var even = function(x) {
return x % 2 !== 0;
};
var add = function(x, y) {
return x + y;
};
function solve(ns) {
// Solve the problem
// with odd or even numbers
var result = function(fn) {
var xs = ns.filter(fn); // odd or even
var sum = xs.reduce(add);
return {
numbers: xs,
sum: sum,
average: sum / xs.length
};
};
// Return an object
// with odd and even results
return {
odd: result(odd),
even: result(even)
};
}
var numbers = [1,2,3,4]; // from user input
var result = solve(numbers);
console.log(result.odd);
//^ {numbers: [2,4], sum: 6, average: 3}
console.log(result.even);
//^ {numbers: [1,2], sum: 4, average: 2}

Categories

Resources