How to find mean of an array using Javascript [duplicate] - javascript

This question already has answers here:
How to compute the sum and average of elements in an array? [duplicate]
(35 answers)
Closed 10 months ago.
I tried to iterate through the array and print the sum. But the output am getting is elements of the array.
<p id="ans"></p>
<script>
var text = "the mean is ";
function mean() {
var sum = 0;
var input = document.getElementsByName("values");
for (var i = 0; i < input.length; i++) {
sum += input[i].value;
text = text + sum;
}
document.getElementById("ans").innerHTML = text;
}
</script>

Parse the string values into integers and then sum it.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
This is because in javascript if you adding a number to a string it will be casted to a string. For example:
0 + '1' + '2' // 012
But with parse int:
0 + parseInt('1') + parseInt('2') // 3
Or you can cast to int with a simple plus also:
0 + (+'1') + (+'2') // 3

Related

How to Add specific values to an array? [duplicate]

This question already has answers here:
Why does console.log return undefined after correct output?
(1 answer)
Javascript even and odd range
(6 answers)
How to append something to an array?
(30 answers)
Closed 9 months ago.
I am creating a function which takes in a minimum and max value. The output should list all the even numbers between these two parameters. I have attempted at creating an array to display these numbers but I get this output:
evenNumbers(4,13) returns: undefined
evenNumbers(3,10) returns: undefined
evenNumbers(8,21) returns: undefined
How to fix my code so it shows the list properly?
var evenNumbers = function(minNumber, maxNumber){
var list = [];
for (let i = minNumber; i < maxNumber; i++){
if (i % 2 == 0){
for(let k = 0; k < maxNumber; k++){
i = list[k];
}
}
}
return console.log(list);
}
console.log('evenNumbers(4,13) returns: ' + evenNumbers(4,13));
console.log('evenNumbers(3,10) returns: ' + evenNumbers(3,10));
console.log('evenNumbers(8,21) returns: ' + evenNumbers(8,21));

With Javascript use a for loop to sum numbers in an array [duplicate]

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
Closed 6 years ago.
I'm trying to find a way to sum all the numbers that have been added to an array. I believe this should work:
var total = 0;
for (var i = 0; i < totalPrice.length; i++);
total += totalPrice[i];
document.getElementById("displayPrice").innerHTML = total;
But total comes out as a NaN.
This is an example of my code in JSFiddle, if you add the item twice the value gets pushed into the array, what am I doing wrong with the for loop?
https://jsfiddle.net/bgv5s9re/2/
You could use brackets
var total = 0;
for (var i = 0; i < totalPrice.length; i++){
total += totalPrice[i];
}
document.getElementById("displayPrice").innerHTML = total;

Separating every 3 numbers with commas [duplicate]

This question already has answers here:
How to format a number with commas as thousands separators?
(50 answers)
Large numbers erroneously rounded in JavaScript
(6 answers)
Closed 6 years ago.
The first thing i want to ask is if there is a more efficient way of writing this programm of mine. The second question is why on earth after a specific number of characters the programm does not function well and prints zeros.
function toCurrency(price) {
var currencyToString = price.toString();
var finalPrice = "";
var counterComma = 0;
for (var i = 0; i < currencyToString.length; i++) {
counterComma++;
finalPrice += currencyToString[i];
if(counterComma == 3){
counterComma = 0;
finalPrice += ",";
}
}
return finalPrice;
}
console.log(toCurrency(123456253635423197874));
https://jsfiddle.net/DimitriXd4/68epen4n/

How do i split an integer and all the digits produced to create a new number? [duplicate]

This question already has answers here:
JavaScript Number Split into individual digits
(30 answers)
Closed 6 years ago.
For instance, if i have the number 4444. I need it to do 4+4+4+4=16.
i want to get the result of 16. I tried changing the number to a string and got the array. But i don't know how to add it after. I searched it up but the other examples were too complicated for my level.
Working Example
var n = 4444;
var a = n.toString().split('').map(Number).reduce(function(a, b) {
return a + b;
});
Turn number to string
Split it
Map over array to return Numbers
Reduce to get total
or with a loop:
var sum = 0;
var string = n.toString();
for (var i = 0; i < string.length; i++) {
sum = sum + Number(string[i]);
}

Adding values in javascript [duplicate]

This question already has answers here:
Plus Arithmetic Operation
(7 answers)
Closed 8 years ago.
I am trying to add up the 2 values (bold) that are inputed by the user but instead of adding then mathematically (100+1 = 101) it adds them like this (100+1 = 1001).
$('#inputcost').keyup(function(){
var price = $(this).val();
});
function checkboxcost() {
var sum = 0;
var gn, elem;
for (i=0; i<2; i++) {
gn = 'extra'+i;
elem = document.getElementById(gn);
if (elem.checked == true) { sum += Number(elem.value); }
}
**var total = (price.value + sum.toFixed(2));
document.getElementById('totalcost').value = "$" + total;**
}
</script>
<input id="totalcost" disabled/>
The problem is, as you suspect, in this line:
var total = (price.value + sum.toFixed(2));
The problem is that .toFixed converts the number to a string for display. So you are trying to add a string to a number, which results in concatenation, not addition.
You want to add the numbers together, then display the sum:
var total = (price.value + sum).toFixed(2);
With that said, I'm not sure where price.value is coming from, so it's possible that's a string too. In which case, convert it with the unary plus + operator:
var total = (+price.value + sum).toFixed(2);
Its treating price.value as String so convert that string to number like:
var total = (Number(price.value) + sum.toFixed(2));
it seems string addition is taking place.
So try converting string numbers to integer using parseInt() like:
var x = parseInt("1")
var y = parseInt("2")
var z = x + y
Try parseInt(price.value) + ...
It's because the types of the operands are strings and the + operator for two strings does concatenation, not addition.
If you convert them to numbers then you'll get a number result:
"1" + "2" == "12"
parseFloat("1") + parseFloat("2") == 3

Categories

Resources