Sum values from an Array, JavaScript - javascript

Prompting the user for many inputs, storing it in an array, then printing summation , average, largest number, smallest number and bigger number than mean number.
I have defined a JavaScript variables called magicnumber which is a new Array , and print the value of array, like this:
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = parseInt(magicnumber.push(prompt("Enter data value number " + i)));
var s = magicnumber.join(', ');
}
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + s + "<br>";
}
<div id="demo1"></div>
how I can summation it?

You can use Array#reduce() to get the sum
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
var promptValue = prompt("Enter data value number " + i);
magicnumber.push(+promptValue);
}
var sum = magicnumber.reduce((a,b)=>{return a+b},0);
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + magicnumber.join(', ');
document.getElementById("sum").innerHTML = "The sum : " + sum;
}
<div id="demo1"></div>
<div id="sum"></div>

Here are 2 more ways to find the summation, without using for loop.
var magicnumber = [];
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = magicnumber.push(parseInt(prompt("Enter data value number " + i)));
}
var data = magicnumber.join(', ');
var s1 = magicnumber.reduce(function(acc, val) {
return acc + val;
});
var s2 = eval(magicnumber.join("+"));
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + data + "<br>";
document.getElementById("demo2").innerHTML = "Sum is: " + s1 + "<br>";
document.getElementById("demo3").innerHTML = "Sum is: " + eval(s2) + "<br>";
}
mymagicNumber();
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>

Related

Need to make a list of the outstanding GPA’s from the array Im making (GPA’s over 3.4). Prefer traditional loop solution over some ES6 function

I need help with getting a list of GPAs over 3.4. I was able to sort largest to smallest, average, and get min and max GPAs utilizing traditional approaches (not ES6).
<div id ="out"></div>
<script>
var gpas = [];
var thegpas = " ";
var total = 0
while (thegpas != "XXX")
{
thegpas = prompt("Enter gpas or XXX to Stop");
if(thegpas != "XXX"){
gpas.push(thegpas);
} else {
break;
}
}
for(var x = 0; x < gpas.length; x++)
{
a = gpas.sort((a,b)=>b-a);
total=total + parseFloat(gpas[x]);
b = total/gpas.length //parseFloat(total)/length;
var max = gpas[0];
var min = gpas[0];
for(var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
}
//need help with this part
//outstandingGPAs=0;
outstandingGPAs = [];
cutoff = 3.4;
if (gpas[x]>cutoff){
outstandingGPAs.push(parseFloat(gpas[x]));
}
out= "Largest to smallest " + a + "<br/>" + "GPAs average: " + b + "<br/>" + " Max and Min: " + max + ", " + min + "<br/>" + "Outstanding GPAs (greather than 3.4): " + outstandingGPAs ;
// alert(gpas[x]);
}
document.getElementById('out').innerHTML=out;
Current Output:
Best way to output a (not very long) array is the join function.
In your output, you should use:
out = "<whatever you put>" + outstandingGPAs.join();
Check this link for more explanation of the join function.
Since you are already looping over your gpas array you could save those that are over 3.4 while you do that.
You would do that within your existing loop, not afterwards.
const cutoff = 3.4;
let outstandingGPAs = [];
// ...
for (var i = 1; i < gpas.length; ++i) {
if (gpas[i]>max) {
max = parseFloat(gpas[i]);
}
else if (gpas[i] < min) {
min = parseFloat(gpas[i]);
}
// added to the existing loop
if (gpas[i] > cutoff) {
outstandingGPAs.push(gpas[i]);
}
}
The outer loop should not be there, as you just redo the same operation over and over again.
As you only push at most one value in outstandingGPAs after you have set it to the empty array, that result will be wrong.
There are several other similar issues going on...
Also, getting input with prompt is really not user-friendly. The way to do this, is using an input element, and let the user type all values freely, and go back and correct whenever they want, and when they are happy with it, they can press a button so the code can run on it.
Here is how that looks:
var calcButton = document.getElementById("calc");
var gpasInput = document.getElementById("gpas");
var outDiv = document.getElementById('out');
calcButton.addEventListener("click", function () {
var min = Infinity,
max = -Infinity,
total = 0,
gpas = [],
outstandingGPAs = [];
// Collect the input as an array of strings with number-related characters
var inputStrings = gpasInput.value.match(/-?\d+(\.\d+)?/g);
for (var i = 0; i < inputStrings.length; i++) {
var num = parseFloat(inputStrings[i]);
gpas.push(num);
if (num > 3.4) {
outstandingGPAs.push(num);
}
if (num < min) {
min = num;
}
if (num > max) {
max = num;
}
total += num;
}
var average = total / gpas.length;
gpas.sort((a, b) => b - a);
// lets also sort the outstanding GPAs
outstandingGPAs.sort((a, b) => b - a);
outDiv.innerHTML = "Largest to smallest " + gpas.join(", ") + "<br>"
+ "GPAs average: " + average + "<br>"
+ "Max and Min: " + max + ", " + min + "<br>"
+ "Outstanding GPAs (greather than 3.4): " + outstandingGPAs.join(", ");
});
Enter gpas values: <input id="gpas">
<button id="calc">Calculate</button><br>
<div id ="out"></div>
Here:
let theGpas = "";
let gpaArr = [];
while(theGpas != "XXX"){
theGpas = prompt("Enter GPAs. Enter XXX to stop.");
if(theGpas != "XXX"){
gpaArr.push(theGpas);
}
}
gpaArr = gpaArr.sort();
document.write("Largest to Smallest: "+gpaArr.join(",")+"<br/>");
function average(array){
var totalSum = 0;
for(var n in array){
totalSum += array[n];
}
return totalSum/array.length;
}
function moreThanArray(array, comparison){
var returnArr = [];
for(var z in array){
if(array[z]>comparison){
returnArr[returnArr.length] = array[z];
}
}
return returnArr;
}
const averageOf = average(gpaArr);
document.write("GPAs average: "+averageOf+"<br/>");
document.write("Max and Min: "+gpaArr[gpaArr.length-1]+", "+gpaArr[0]);
document.write("<br/>"+"Outstanding GPAs (greater than 3.4): "+moreThanArray(gpaArr, 3.4).join(","));

Printing particular element of set container in javascript

I am new to javascript. I want to fetch a particular element from set container.
Here is my source code:
var i, item, val = '';
var setObj1 = new Set();
for (i = 0; i < 5; i++) {
setObj1.add(i);
}
for (item of setObj1.values()) {
val += item + ' ';
}
document.getElementById('demo').textContent = "The set values are: " + val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + setObj1.values[1];
<div id="demo"> </div>
<div id="demo1"> </div>
Please correct my syntax or suggest me a approach to print particular index value of set.
You can do it like this
var i, item,val = '';
var setObj1 = new Set();
for(i=0;i<5;i++){
setObj1.add(i);
}
for (item of setObj1.values()){
val+=item + ' ';
}
var iterator = setObj1.values();
iterator.next();
document.getElementById('demo').textContent = "The set values are: "+val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: "+ iterator.next().value;
Note: If you want to get values with their index it would be better to use arrays instead of Set
Although you can do that, it's expensive. Sets aren't for index-oriented or key-oriented operations (use an array or Map for that).
The expensive way is to converting the set to an array (which uses values indirectly through the set's iterator and iterates all the way to the end to get the full set) and index into the array:
document.getElementById('demo1').innerHTML = [...setObj1][1];
Live Example:
var i, item, val = '';
var setObj1 = new Set();
for (i = 0; i < 5; i++) {
setObj1.add(i);
}
for (item of setObj1.values()) {
val += item + ' ';
}
document.getElementById('demo').textContent = "The set values are: " + val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + [...setObj1][1];
<div id="demo"> </div>
<div id="demo1"> </div>
But here's your example using an array instead:
var i, item, val = '';
var values = [];
for (i = 0; i < 5; i++) {
values[i] = i;
}
document.getElementById('demo').textContent = "The set values are: " + values.join(" ");
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + values[1];
<div id="demo"> </div>
<div id="demo1"> </div>

Sum up html string numbers using javascript

Hello I have a function that returns numbers inside a <p> tag with the following format:
<p class="numbers">123 + 456 + 789</p>
Is there any way I can do another function or something in javascript to sum up all the numbers and store it into a variable?
Thanks!
// Grab the element
const para = document.querySelector('.numbers');
// Convert the text content to an array and
// make the text number values into actual numbers
const numbers = para.textContent.split(' + ').map(Number);
// Use `reduce` to sum the numbers
const total = numbers.reduce((p, c) => p + c);
DEMO
This should do it:
var string = "<p class="numbers">123 + 456 + 789</p>";
var numbers = string.split(">")[1].split("<")[0].split("+");
var i = 0;
var sum = 0;
while(i < numbers.length){
sum += parseInt(numbers[i]);
i += 1;
}
return sum;
You can use Array.prototype.reduce()
var n = document.querySelector(".numbers").textContent;
var nums = n.replace(/\s/g, "").match(/^\d+|[+-]\d+/g);
var res = nums.reduce((a, b) => Number(a) + Number(b));
document.body.innerHTML += `=${res}`;
<p class="numbers">123 + 456 + 789</p>
var x = document.querySelector('.numbers').textContent.split("+").map(Number);
var y = x.reduce(function(add,num){return add+num})
console.log(y);

How to declare a variable with no value?

The following code is what I am using to convert a hex to binary. To print binary out, I add individual strings to a previously declared blank variable. However, this prints out "undefined + binary". Is there a way to declare a variable with no value --even undefined. If not is there a better way to concatenate variables in a for loop without a previously declared variable?
All help will be appreciated!
var integer = prompt("Insert hex digit");
var userHexDigits = [];
var hexDigits = [0, 1,2,3,4,5,6,7,8,9,'a','b','c','d','e','f'];
var binaryDigits = ['0000', '0001','0010','0011', '0100','0101','0110','0111','1000','1001','1010','1011','1100','1101','1110','1111'];
var hexy = [];
var binary
for(i = 0; i < integer.length; i++) {
digit = i + 1;
document.write("Your digit #" + digit + " is: " + integer[i] + "<br/>");
userHexDigits.push(integer[i]);
}
for (var m = 0; m < userHexDigits.length; m++) {
hex = userHexDigits[m];
for(k =0; k < hexDigits.length; k++) {
if (hex == hexDigits[k]){
binary += binaryDigits[k] + " ";
}
}
}
document.write("<br/><br/>The number " + integer + " in binary is " + binary);
If you want a string variable with an empty value just:
var binary = "";

issue with adding values from array

I am writing a small application for the user to enter the name of a book and then its price, push the values of those to an array, output the book name and cost to the page and then display the total.
the issue I am having is with the total, for example:
If I write 2 as the value of each of the values, the "totalOutput" says 022222 instead of 10 as I would expect, I have tried a few different things and read a few articles on here but haven't found any to be much help or that useful.
these are the exact lines I am having issues with:
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
And incase you need it - here is my full javascript code:
//Book shop task
function trackBooks() {
//target the output ul and store in a variable
var output = document.getElementById("booksOutput");
//Setup the two arrays to hold the book names and their prices.
var books = [];
var price = [];
//declare a variable for working out the total
var total = 0;
//target the total output
var totalOutput = document.getElementById("totalOutput");
//set up a counter for the loop
var x = 0;
//setup the loop for entering the names of the books and their prices, for the sample, I have set the loop to run 5 times as stated in the pseudo code
for (var i = 0; i < 5; i++) {
//add one to the counter on each loop
x = x + 1;
//declare a variable to ask the user for the book name and the cost and push those values to their arrays we created above
var bookName = prompt("enter book name number " + x);
books.push(bookName);
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
//create a variable to create new li tags on output
var newLi = document.createElement("li");
//add the required info to the new link
newLi.innerHTML = "book " + x + ": " + "<strong>" + books[i] + "</strong>" + " costs " + "<strong>" + price[i] + "</strong>";
//write out the name and price to the page
output.appendChild(newLi);
}
//go over each item in price and add up the total
price.forEach(function addNumber(value) {
total += value;
});
//write the total
totalOutput.innerHTML = "the total value of the books is " + total;
}
var bookPrice = prompt("how much does book number " + x + " cost?");
price.push(bookPrice);
prompt returns a string, and when you add a number (0) and a string ("2"), you get a string ("02"). You should cast to number here:
price.push(+bookPrice);
(unary + casts to a number)
You are adding Strings not a Numbers. For example:
"Hello " + "World";
Will output "Hello World".
"10" + "20";
will output "1020"
Instead you have to convert the String to a Number
Number("10") + Number("20");
will ouput 30
To apply this to your code:
price.push(Number(bookPrice));

Categories

Resources