How do I divide the sum with 2 after a loop, so I get the value 38? I want to print out the answer in an alert box.
My Javascript code:
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum);
Or if I have the values 1, 2, 3, 4, I want to get the sum (in this case 10) in the loop and divide it with 2 and print out it in an alert box.
//variable declaration and loop above
alert(sum/2);
You need to divide by 2 then...
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
sum /= 2;
alert(sum);
var nums = ['1','75'];
let sumDiv2 = (nums)=> {
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += Number(nums[i]);
}
return sum
}
alert(sumDiv2(nums)/2);
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum/2);
This isn't complex to solve.
Using array reduce method you can do like below
var arr = ["1", "67"];
var divide = arr.reduce(function (acc, ele) {
return acc += +ele; // To convert element from string to array use +
}, 0) / 2;
console.log(divide);
You can do it on 1 line.
var nums = ['1','2', '3', '4'];
var result = nums.reduce((el, acc) => parseInt(el) + parseInt(acc), 0) / 2;
console.log(result);
var nums = ['1','75'];
var sum = 0;
for(var i=0; i < nums.length; i++){
sum += parseInt(nums[i]);
}
alert(sum/2);
You can try this without any loop. Short, simple and stylish:
var arr=['1', '75'],
sum_2=arr.reduce(function(a,b){return a*1+b*1;},0)/2;
alert(sum_2);
console.log(['1','2'].reduce((p,c) => +p + +c, 0) / 2)
// ^ ^ ^ ^ ^
// | | | | |
// "p" as "previous"_| | |____| |_first "p" value
// | |
// "c" as "current"_| |_convert strings to integers
Run the snippet; what happens:
.reduce() starts on the ['1','2']
In the first call to the inner function ((p,c) => +p + +c) the value of p(revious) is 0, as the second argument passed to the .reduce(), and value of the c(urrent) is '1', the first array element; the 0 + +'1' executes, resulting in 1
In the second call to the inner function the value of p is 1 - from previous execution, and the value of c is '2'; the 1 + +'2' executes, resulting in 3
As here are no more items in the array, the final result of .reduce() call gives as 3, which is then divided by 2 in 3 / 2, resulting in 1.5
Unary operator + preceding string (+'1', '+'2'`) converts the string into integers.
You could divide the sum by 2.
BTW, while you have already integer values as strings, you could use an unary plus + for a conversion to number.
sum += +nums[i];
// ^
var nums = ['1', '75'],
sum = 0,
i;
for (i = 0; i < nums.length; i++) {
sum += +nums[i];
}
alert(sum / 2);
Related
The question I'm trying to solve is:
Find the sum of the series (3 + 33 + 333 + 3333 + ... + n), to n terms, where n is an input provided by the user (using prompt).
Example: Given 5. So the series will become (3 + 33 + 333 + 3333 + 33333).
Expected output: 37035
This is my code:
const number = 5;
let sum = 3;
let add;
for (i = 0; i <= number; i++){
add = "";
for (j = 1; j <= i; j++) {
add += 3;
sum = add * 10 + 3
}
sum = sum + *5;
}
console.log(sum);
It's not giving me the desired outcome (which is obviously the issue I'm running into). I haven't used prompt yet because I don't know how to implement it. Could someone please help me?
You don't need a nested loop. Use just a single loop, and inside, increment add based on the power of 10 of the current iteration, and add the result to the sum:
const count = 3
let sum = 0;
let add = 0;
for (i = 0; i < count; i++){
add += 3 * 10 ** i;
sum += add;
}
console.log(sum);
You can use the padEnd() method to add padding at end of a string. Please check the snippet for the solution by using the padEnd() method. In this way, you can avoid string concatenation or extra loop.
Please check the link to know more about the method padEnd
const count = 5;
let number = 3;
let sum = 0;
for(i = 1; i <= count; i++) {
sum += Number(number.toString().padEnd(i, number.toString()));
console.log(i.toString() + ". " + number.toString().padEnd(i, number.toString()));
}
console.log("Sum: " + sum);
Here is what you ask i think, so i turn to string the iteration number in order to add it to an array and then reduce javascript property to sum all it's elements!!
const number = 5;
let sum = 3;
let added = '';
let add = [];
sum = sum.toString();
added = sum;
for(let i = 0; i<number; i++){
add.push(added);
added += sum;
}
let result = add.reduce((ant,sum)=>{
return parseInt(ant) + parseInt(sum);
});
console.log(result);
Edit: for the prompt question here's a link that i hope it helps you!
You can use it this way: const number = prompt("enter how much numbers");
Here's how you can do it:
const sumNum = 3;
const number = Number(prompt('Please enter a number for repeatitions: '));
let sum = '';
for (let i = 0; i < number; i++) {
for (let j = 0; j <= i; j++) {
sum += sumNum;
}
if (i < number) sum += '+';
}
let total = 0;
sum = sum.split('+');
sum.pop(); //to remove last empty field
while (sum.length) {
total += Number.parseFloat(sum.shift());
}
console.log(total);
To repeat a number:
const x = 3;
Number(`${x}`.repeat(1)); //=> 3
Number(`${x}`.repeat(2)); //=> 33
Number(`${x}`.repeat(3)); //=> 333
Number(`${x}`.repeat(4)); //=> 3333
Number(`${x}`.repeat(5)); //=> 33333
So from such array [3, 3, 3, 3, 3] we can do:
[3, 3, 3, 3, 3].map((x, i) => Number(`${x}`.repeat(i+1)));
//=> [3, 33, 333, 3333, 33333]
But we don't need to manually fill an array with n identical numbers:
const n = 5;
const x = 3;
Array(n).fill(x);
//=> [3, 3, 3, 3, 3]
Or:
Array.from(Array(n), () => x);
//=> [3, 3, 3, 3, 3]
But obviously if we can apply a function on each item we may as well produce the full series:
Array.from(Array(n), (_, i) => Number(`${x}`.repeat(i+1)));
//=> [3, 33, 333, 3333, 33333]
Finally we can reduce the series to the sum of all numbers:
[3, 33, 333, 3333, 33333].reduce((tot, x) => tot + x, 0);
//=> 37035
So altogether we have:
const n = 5; // use prompt() but don't forget to coerce the result into a number
const x = 3;
Array.from(Array(n), (_, i) => Number(`${x}`.repeat(i+1)))
.reduce((tot, x) => tot + x, 0);
If you don't need to produce a series then a recursive function is perhaps simpler:
const sum_series =
(x, n, tot=0) =>
n === 0
? tot
: sum_series(x, n-1, tot+=Number(`${x}`.repeat(n)))
sum_series(3, 5);
//=> 37035
my array from user input: [1,2,3,4]
what I want:
[1,2,3]*[2,3,4]
(1*2) + (2*3) + (3*4) = 20
what I have so far:
var array = [];
var number= document.getElementById("number").value; //this is where user inputs the number for my array
var sum = 0;
for (var i = 0; i< number.length; i++){
array.push(parseInt(number[i]));
var first= number[i-1];
var second = number[i+1];
sum += (first*second);
}
console.log(sum);
that is my solution with reduce method of array
[1, 2, 3, 4].reduce((a, c, i, s) => (s[i + 1] ? c * s[i + 1] + a : a), 0);
No need for an array for this.
In the following pattern: (1*2) + (2*3) + (3*4) you can see how this can occur using for loop without array.
Following works:
var number= parseInt(document.getElementById("number").value); //this is where user inputs the number for my array
var sum=0;
for (var i = 1; i< number; i++){
sum += i*(i+1);
}
console.log(sum);
You could use slice to get subsets of the arrays and then use reduce to create the sum like this:
const arr = [1,2,3,4]
const first = arr.slice(0, -1)
const last = arr.slice(1, arr.length)
const result = first.reduce((acc, num, idx) => acc + num * last[idx], 0)
console.log(result)
Sorry if I get my terms wrong I am new to this!
What I am trying to do is get the user to input 4 digits, put those into an array, and then multiply those numbers by itself, then return the sum. Example:
User inputs 1234
What I want it to do: [1, 2, 3, 4]
The math I want: (1*1) + (2*2) + (3*3) + (4*4)
output: 30
This is what I have done:
arr = [];
var number= parseInt(document.getElementById("number"));
arr.push(number);
var sum = 0;
for (var i = 0; i< arr.length; i++){
sum += (arr[i]*arr[i]) ;
}
console.log(sum);
Where am I going wrong? Thanks!
arr is an array with one element, the entire number that the user entered.
You need to split the input into separate numbers for each digit.
Also, you have to use the .value property to get what the user entered.
arr = [];
var number = document.getElementById("number").value;
for (var i = 0; i < number.length; i++) {
arr.push(parseInt(number[i]));
}
I've provided full example with comments. I hope this is what you are looking for.
const doMagic=(numberInput)=>{
// if it doesn't have value, return false
if (!numberInput && numberInput.value) return false;
// split input value by each character
const arr = numberInput.value.split('');
let sum = 0;
for (var i = 0; i < arr.length; i++)
sum += (arr[i]*arr[i]);
return sum;
}
// get element, not value
const numberInput = document.getElementById("number");
// on elements value change call our function
numberInput.addEventListener('change',()=>
console.log(doMagic(numberInput))
);
<input id="number" type="number"/>
The purpose of this to teach you loop, not array and slice, You can do this using simple while loop and mathematics.
// var number = parseInt(document.getElementById("number"));
var number = 1234;
let sum = 0;
for (; number > 0; ) {
const x = Math.floor(number % 10);
sum += x * x;
number = Math.floor(number / 10);
}
console.log(sum);
Try this.
arr = [];
var number= document.getElementById("number");
arr = number.split("");// Splits the input into a string array like ["1","2","3","4"]
var sum = 0;
for (var i = 0; i< arr.length; i++){
sum += (arr[i]*arr[i]) ;
}
console.log(sum);
Note: JS is very loose when it is trying to check for type of input.
Input is assumed to be always of integer format.
try this :
const input = document.getElementById("number");
const arr = [...input.toString()];
const sum = arr.reduce((total, item) => {
const num = parseInt(item);
const multipy = num * num;
return (total += multipy);
}, 0);
console.log(sum);
You could use the legible for-of syntax -
const numbers = [ 1, 2, 3, 4 ]
let result = 0
for (const num of numbers)
result = result + (num * num)
console.log(result) // 30
You could also use Array.prototype.reduce -
const numbers = [ 1, 2, 3, 4 ]
const result = numbers.reduce((result, num) => result + (num * num), 0)
console.log(result) // 30
Here is the answer (please click on Run code Snippet)
function getTotal() {
arr = [];
// you forget to put .value here
var numbersAsAString = document.getElementById('number').value;
// => 1234
// and you need to take each digit from the input you insert
for (var i = 0; i < numbersAsAString.length; i++) {
// and as you did parseInt to convert string to number
arr.push(parseInt(numbersAsAString[i]));
}
// console.log(arr); // [1,2,3,4]
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i] * arr[i];
}
// console.log(sum);
document.getElementById('answer').innerHTML="Answer will be here: "+sum;
}
// If you need any explanation, or this is not what you are asking about, please comment on my answer
<html>
<head>
<title>StackOverFlow 🍗</title>
<link rel="shortcut icon" type="image/x-icon" href="https://image.flaticon.com/icons/png/512/2057/2057586.png" />
</head>
<body>
<h3>Stack Over Flow 🍗</h3>
<input id="number" type="text" value="1234">
<button onclick="getTotal()">get the answer</button>
<p id="answer">Answer will be here: </p>
</body>
</html>
If you need any explanation, or this is not what you are asking about, please comment on my answer
I am trying to create a function that adds all arguments together. I keep getting NaN. What am I doing wrong?
function sum() {
var n = arguments.length;
var total = 0;
for(var i = 0; i < n; i++) {
// code here
total += n[i];
}
return total;
}
sum(1,2,3,4);
You need to get value from arguments, where n is just a number holds the length of arguments and n[i] will be undefined. Addition with undefined results NaN.
function sum() {
var n = arguments.length;
var total = 0;
for (var i = 0; i < n; i++) {
// code here
total += arguments[i];
}
return total;
}
console.log(sum(1, 2, 3, 4));
What is n[i]; ? As n should only contain length of arguments array, its not itself an array.
You need to replace total += n[i]; with total += arguments[i];
One of the classic disadvantage of javaScript is about NaN(Not a Number)'s underlying principle is.
NaN(Not equal to anything)-->When it occurs
i)Result of undefined or erroneous operations
ii)Toxic :any arithmetic operations with Nan as input will have NaN as a result.
So in your code:undefined(n[i])+number=NaN
<script>
function sum() {
var n = arguments.length;
var total = 0;
for (var i = 0; i < n; i++) {
// code here
total += arguments[i];
}
return total;//returns 10
}
sum(1, 2, 3, 4);
Hope this helps/serves the purpose
I have array like this in JavaScript
var a = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"];
My questions are
How do I split the array to change, (comma) to ";"
How do I return the number of strings in the array as well as return total value regardless of variable type.
How do I return the average value (regardless of variable type again)
Answering Question 1
1.Convert it to a string
var x=a.toString();
2.Perform a global replace
var y= x.replace(/,/g,";");
3.This gives you "1;2;3;4;5;4;12;2;6;7;4;3;2"
For Question 2
Simply use the a.length method.This will give you the total number of elements.I'm not sure about the String elements part.
Change array separator:
a.join(';');
as referenced here
Number of strings in array:
var stringCount = 0;
for (var i = 0; i < a.length; i++){
if (typeof a[i] === 'string'){
stringCount++;
}
}
alert("The number of strings is: " + stringCount);
Test it here: https://jsfiddle.net/6c42nugy/2/
Number of all elements in array:
var entireLength = a.length;
Percentage per type in comparison to whole
var stringPerc = (stringCount)/(stringCount + entireLength)
var otherPerc = (entireLength - stringCount)/(stringCount + entireLength)
Use a.join(';'); to convert the array into a string separated by semicolons.
To return the number of strings in the array, simply iterate through it and use toString.call() like this:
var total = 0;
for (var i = 0, n = a.length; i < n; i++) {
if (toString.call(a[i]) === '[object String]') total++;
}
To simply return the total number of items, you can do a.length.
If you want the total value as in all the elements summed, you can do this:
var total = 0;
for (var i = 0, n = a.length; i < n; i++) {
total += parseInt(a[i]);
}
If you want the average, just take the code above and do total / a.length;.
Here is my version:
var a = [1,2,3,4,5,"4","12","2",6,7,"4",3,"2"], sum = 0, strings = 0;
var joined = a.join(';');
console.log("Joined: " + joined);
for (var i = 0; i < a.length; i++) {
sum += parseInt(a[i]);
if (typeof a[i] === "string") {
strings++;
}
}
var avg = sum / a.length;
console.log('Sum: ' + sum);
console.log('Average: ' + avg);
console.log('Strings: ' + strings);
And link to JSFiddle.
All results in one loop.
0 ... n-4: Data
n-3: Count of all strings
n-2: Sum
n-1: Average
var data = [1, 2, 3, 4, 5, "4", "12", "2", 6, 7, "4", 3, "2"],
result = data.concat(data.reduce(function (r, a, i) {
typeof a === 'string' && r[0]++;
r[1] += +a;
r[2] = r[1] / i;
return r;
}, [0, 0, 0])).join(';');
document.write('<pre>' + JSON.stringify(result, 0, 4) + '</pre>');