var num = prompt("Enter a number");
for (var sum = 0; sum <= num; sum++) {
sum = sum + 1;
}
document.write(sum);
example when I enter 6 in the prompt it will sum 1+2+3+4+5+6 =21. but as of right now i can only print 123456 instead of 21.
Input received by you is a string and that's why it's contacting rather than adding to sum.
This is the best optimum solution as its time complexity is O(3) times only.
so, it's fast. rather than with brute force which is o(n);
var num = prompt("Enter a number");
function total(n) {
return n * (n + 1) / 2;
}
document.write(total(parseInt(num)));
The problem with your code is that you're using sum for the loop and for the answer. That's messing everything up. You can use a variable for the loop and another variable for the sum.
Maybe that works for you.
var num = prompt("Enter a number");
var sum = 0;
for(var i = 1; i <= num; i++) {
sum += i;
}
document.write(sum);
here is some change in your code.
note: (+) is used to convert string-number type to number type
var num = prompt("Enter a number");
const sum = Array.from(Array(+num + 1).keys()).reduce((prev, curr) => prev += curr, 0);
document.write(sum);
I have the following JSON array:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
How can I calculate all the "price" values together? The result should be 8.
I have so far the following but problems accessing the price items:
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum = sum + fruits[i][price];
}
return sum;
}
console.log(count(fruits)
Thank you!
You need to access them like:
fruits[i].price
and then convert them to numbers before adding them:
parseInt(fruits[i].price, 10);
Final code:
fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
var total = 0;
for(var i=0; i<fruits.length; i++){
total += parseInt(fruits[i].price, 10);
}
alert(total); //8
See the DEMO here
Two things:
The line
sum = sum + fruits[i][price];
should be
sum = sum + fruits[i].price;
or even
sum += fruits[i].price;
Your code was trying to use a variable called price, not the price property of the fruit entry.
Your prices are strings, so we want to make sure they're converted to numbers when summing them up. You have lots of options there: Apply a unary + to them, pass them into Number(), or use parseInt(..., 10). Below I'll go with a unary +, but there are pluses (no pun!) and minuses to each.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
for (var i = 0; i < fruits.length; i++) {
sum += +fruits[i].price; // <=== change is here
}
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
With ES5's array additions (which can be shimmed on older browsers), you can do this with either forEach or reduce:
forEach:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
fruits.forEach(function(fruit) {
sum += +fruit.price;
});
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
reduce:
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(fruits) {
var sum = 0;
sum = fruits.reduce(function(prev, fruit) {
return prev + +fruit.price;
}, 0);
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
Your code has 2 errors:
To access the price property
fruits[i][price]
should be
fruits[i]['price'] or fruits[i].price
The price property is of type string. So the '+' operator will concatenate the price strings. To add them together you need to change their type to number by doing
parseInt(fruits[i]['price'], 10) or +fruits[i]['price']
If the price property doesn't contain a valid number the result will be NaN (not a number). You could avoid that by using the or operator.
+fruits[i]['price'] || 0
Using the ES5 Array extensions supported by all modern browsers you could write
fruits.reduce(function(m,v) { return m + (+v.price);}, 0);
With ES6 in future browsers this could be reduced to
fruits.reduce((m,v) => m + (+v.price), 0);
You have some errors in your code.
The first one is here: sum = sum + fruits[i][price];
you are trying to use a variable called price, not the property price of the object. You can access to the property using fruits[i]["price"] or fruits[i].price.
To obtain a number, when you are doing the sum, you need to convert the strings in numbers, to do that you can use parseInt(fruits[i]["price"]);. Last error in the last line you forgot the parenthesis and semicolon.
JSFiddle
your function is OK, just add parseInt for it to convert to type int, and has a incorrect syntax in fruits[i][price].
You've two option:
fruits[i]["price"]
OR
fruits[i].price
In my opinion, I would add a small logic code to check if it's a number or not. and return 0 if input data is undefined or null.
var fruits = [{"fruit":"banana","amount":"2","price":"1"},{"fruit":"apple","amount":"5","price":"2"},{"fruit":"kiwi","amount":"1","price":"5"}]
function count(data) {
var sum = 0;
if(data === void 0 ) return 0; // no array input
data.forEach(function(fruit) {
console.log(fruit);
sum += parseInt(fruit.price || 0 ); // if price is undefined, null or NaN, return 0
})
return sum;
}
display(count(fruits));
function display(msg) {
var p = document.createElement('p');
p.innerHTML = String(msg);
document.body.appendChild(p);
}
You should try this simple code snippet.
You don't need jQuery to do this operation. Simple JS would do.
var sum = 0;
for(var item in fruits){
sum += ~~(fruits[item].price)
}
console.log(sum)
Cheers!
Here, sums[i].value is getting right values but when I want to keep a grand total of all Sum, it is failing.
function calc() {
var amounts = document.getElementsByName("Amount");
var prices = document.getElementsByName("Price");
var sums = document.getElementsByName('Sum');
var tax = document.getElementsByName('Tax');
var total = document.getElementsByName('Total');
for (var i = 0; i < amounts.length; i++) {
sums[i].value = amounts[i].value * prices[i].value;
total[0].value = total[0].value + sums[i].value;
// only this line is not working
}
}
Plain HTML is strings, all the way down, and var amounts = document.getElementsByName("Amount"); followed by amounts.value means you now have string values. Since + is also a string operator, JavaScript will happily turn "2"+"4" into "24", which looks like it did maths, but wrong, when in fact it didn't do math at all.
Convert all values that need to be numbers into numbers, first:
var amounts = document.getElementsByName("Amount");
....
var amount = parseFloat(amounts.value); // NOW it's a number
...
Replace your code with :
for (var i = 0; i < amounts.length; i++) {
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
// only this line is not working
}
sums[i].value = parseFloat(amounts[i].value) * parseFloat(prices[i].value);
total[0].value = parseFloat(total[0].value) + parseFloat(sums[i].value);
This should help you.
Remove the .value while adding and multiplying
function test()
{
var amounts = new Array();
amounts[0] = "4";
amounts[1] = "6";
amounts[2] = "10";
var prices = new Array();
prices[0] = "4";
prices[1] = "6";
prices[2] = "10";
var sums = new Array();
var total = 0;
for (var i = 0; i < amounts.length; i++) {
sums[i] = parseInt(amounts[i]) * parseInt(prices[i]);
total= parseInt(total) + parseInt(sums[i]);
// only this line is not working
//alert(total); is 152
}
}
How to add values from all input with name name="TotalInline[]"?
The following does not seams to work:
var total = 0;
$.each('input[name="TotalInline[]"];,function() {
total += this;
});
This should work :
var total = 0;
$('input[name="TotalInline"]').each(function() {
// assuming you have ints in your inputs, use parseFloat if those are floats
total += parseInt(this.value, 10);
});
var total = 0;
$.each($('input[name="TotalInline[]"]'), function() {
total += parseInt(this.value, 10);
});
You have some serious syntax errors, try this:
var total = 0;
$('input[name="TotalInline[]"]').each(function () {
total += parseInt(this.value, 10);
});
Try like this...
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += parseInt($(this).val(),10);
});
var total = 0;
$('input[name="TotalInline[]"]').each(function() {
total += +this.value.replace(/[^\d.]/g, '');
});
Uses a quick regex to filter out only the numbers (and decimal point).
Uses a + prefix to convert to a number.
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))