Squaring each number in an array with dynamically added inputs - javascript

I'm trying to calculate the standard deviation of a set of data entered by a user into a form with dynamically added inputs. Thus far I have been able to calculate the sum of the elements in the array, but I cannot figure out how to square each element of the array. I have searched this forum, but trying suggestions from the only applicable result (Square each number in an array in javascript) did not seem to work. Here is a snippet of my code:
$(".calcSD").click(function() {
$("input[type=text]").each(function() {
arr.push($(this).val().trim() || 0);
sum += parseInt($(this).val().trim() || 0);
});
Where .calcSD is the button the user clicks to perform the calculation. Moreover, the length of the array is given by var number = arr.sort().filter(Boolean).length; as the script is intended to filter out any inputs that are left blank.
Also, if it make a difference, inputs are dynamically added to the array via:
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).unbind('click').click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
So I ask: how would go about determining the square of each element in the resulting array?

The pow() method returns the value of x to the power of y (x^y)
|| in parseInt will use base as 0 if it returns falsey value
$(".calcSD").click(function() {
var sum = 0;
var arr=[];
$("input[type=text]").each(function() {
var squared = Math.pow(parseInt(this.value)||0, 2);
arr.push(squared);
sum += squared;
});
alert(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text">
<input type="text">
<button class="calcSD">Calculate</button>

I might not have followed you correctly, but couldn't you just multiply the value by itself as it's pushed to the array?
$(".calcSD").click(function() {
$("input[type=text]").each(function() {
arr.push(($(this).val()*$(this).val()).trim() || 0);
sum += parseInt($(this).val().trim() || 0);
});

Ultimately I wanted to be able to sum the squares of the elements in the array (as it is a part of calculating the SD) so I did this and it works:
var sumXsq = 0;
for(var i = 0 ; i <= number ; i++) {
sumXsq += parseInt(arr[i]*arr[i]);
}
but not quite as good as Rayon's answer.

Related

How to compare the values in a list and the value that is compared to will be inserted to the front or back if its larger or smaller?

I am creating a function that inserts an element into a list only if the element to be inserted
is larger than any of the elements currently in the list. Larger can mean either greater
than when working with numeric values, or further down in the alphabet, when
working with textual values.
var names = new List();
function List(){
this.dataStore = [];
this.listSize = 0;
this.pos = 0;
this.append = append;
}
function append(element){
for (i = 0; i > this.dataStore.value;++i){
if (names.value == this.dataStore[i].value){
this.dataStore[this.listSize++] = element;
this.pos++;
}
}
}
function insert(element, after) {
var insertPos = this.find(after);
if (insertPos > -1) {
this.dataStore.splice(insertPos+1, 0, element);
++this.listSize;
return true;
}
return false;
}
function find(element){
for (var i = 0; i < this.dataStore.length;++i){
if(this.dataStore[i]== element){
return i;
}
}
return -1;
}
names.append("Jascien");
console.log(names);
names.append("Jas");// i want to insert this value after its compared to the exiting values in the front of the first value or after it.
console.log(names);
names.append("John"); // also this one
console.log(names);
By numeric values you mean number as string, or number as Number. If number as Number, then I think it would be good to divide this condition check in two separate condition check, depending on type of data entered as element.
As written above, please provide some input and output arrays for better understanding what you expect from this function.

Trying to generate & display non-repeating random values for a BINGO game

I am working on making a bingo game. I've gotten as far as being able to get a random number generated and displayed at the click of a button. My only issue is that some values will end up being generated more than once. THAT IS THE PART I'M POSTING THIS QUESTION FOR. EVERY VALUE SHOULD ONLY BE GENERATED & DISPLAYED ONCE UNTIL THE GAME IS RESET. Does anybody have any example code, preferably for how to use something like the splice() method that I keep hearing brought up?
I CAN ALREADY GENERATE THE RANDOM NUMBER FROM THE SET AND DISPLAY IT. I'M ONLY LOOKING TO MAKE SURE THAT NUMBERS THAT ARE GENERATED ARE NOT REPEATED.
<head>
<title>BINGO</title>
</head>
<body>
<div id="bingo">
<script>
let numbers = new Set()
.add("B1")
.add("B2")
.add("B3")
.add("B4")
.add("B5")
.add("B6")
.add("B7")
.add("B8")
.add("B9")
.add("B10");
let called = Array.from(numbers);
let display = new Array();
function getRandomNum()
{
function rando()
{
for (let i = called.length - 1; i > 0; i++)
{
const j = Math.floor(Math.random() * called.length);
const number = called[i];
called[i] = called[j];
called[j] = number;
return number;
//let show = called[Math.floor(Math.random() * called.length)];
//return show;
}
//document.getElementById('bingo').innerHTML = display[0];
}
let index = rando();
document.getElementById('bingo').innerHTML = index;
display.push(index);
}
function show()
{
for(let n = 0; n < display.length; n++)
{
document.getElementById('reveal').innerHTML += "<br/>" + display[n] + "<br/>";
}
}
</script>
</div>
<div id="button">
<button onclick="getRandomNum()">Random Number</button>
</div>
<br/>
<br/>
<br/>
<div id="reveal">
<button onclick="show()">Numbers Called</button>
</div>
</body>
</html>
Looking for some help to prevent number generated from being repeated (EXAMPLE CODE PREFERRED)
You could create an array in which you store all numbers which have already been selected. Then, when randomly selecting a new number, continue to randomize until a number has been selected which is not within that array of already-chosen numbers.
Here's a code example which illustrates this idea, picking numbers between 0 and 9, not allowing repeat numbers. The process is broken down below.
var alreadyPicked = [];
var max = 10;
function random() {
let unique = false;
while (!unique && alreadyPicked.length < max) {
let randNumber = Math.floor(Math.random() * max);
if (alreadyPicked.includes(randNumber) == false) {
unique = true;
alreadyPicked.push(randNumber);
}
}
}
An array, alreadyPicked, is declared. It serves to keep track of which numbers have already been selected, so that they won't be selected twice.
The number max is declared. It is used to prevent an infinite loop when there are no more random numbers to choose.
Random numbers are chosen in the while loop, which loops either until the unique boolean is set to true or until the length of the alreadyPicked array has reached the max length, which happens when there are no more unique numbers to select.
Once a number is obtained, the statement alreadyPicked.includes(randNumber) checks to see whether the randNumber is among those numbers already selected and stored in alreadyPicked.
If this is false, this means a unique number has been selected. unique is then set to true to break the loop, and the number is pushed to alreadyPicked so that it won't be selected again.
<head>
<title>BINGO</title>
</head>
<body>
<div id="bingo">
<script>
let numbers = ["B1", "B2", "B3", "B4", "B5", "B6", "B7", "B8", "B9", "B10"]
let display = [];
function getRandomNum() {
function rando() {
for (var i = 0; i < numbers.length; i++) {
const j = Math.floor(Math.random() * numbers.length);
const number = numbers[j];
if (number) {
numbers.splice(j, 1);
}
if (numbers.length < 0) {
return
} else {
return number;
}
}
}
let index;
if (numbers.length === 0) {
index = "No more numbers"
} else {
index = rando();
display.push(index);
}
document.getElementById('bingo').innerHTML = index;
}
function show()
{
for(let n = 0; n < display.length; n++)
{
document.getElementById('reveal').innerHTML += "<br/>" + display[n] + "<br/>";
}
}
</script>
</div>
<div id="button">
<button onclick="getRandomNum()">Random Number</button>
</div>
<br/>
<br/>
<br/>
<div id="reveal">
<button onclick="show()">Numbers Called</button>
</div>
</body>
</html>
Here is the example with splice.
Forget everything you done .
Start creating an array using range function, set number of numbers as you like .
Than, you need to use a seed to make the pseudo-randomness better .
So, instead of rand, you gotta use SHUFFLE,
so you set array on range as 1 to 90, set the seed, than use shuffle to shuffle the array.. than you got all numbers in a random order (corresponding to the seed) .
You gotta change the seed to have another result .
The order of the numbers is the result .
as .. ball 1 : 42 ... ball 2: 10.... ball 3: 50.... ball 1 is 0 in the array. ;)
You can also use slice function and create a for / each loop, incrementing the slice factor, so you loop
slice array 0,1 the the result .. ball 1...
slice array 0.2 ball 2...
slice array 0.3
Thats the logic, i hope you understand, if so .. it ill help you a lot .
The way I did this was to shuffle an array of numbers from 1-90 and then call those numbers in sequence. They've already been shuffled, so they're already random.

JavaScript calculation returns NaN

I want to find total sum of passing the field values in array. If the field is for discount then perform minus else plus. For some reason I'm getting nan.
Here is my script code
<script>
var partial_cost = $('#bill_amount:disabled').val();
var fine = +$('#fine').val();
var discount = +$('#discount').val();
var other_cost = +$('#other_cost').val();
var total_cost = +$('#total').val();
var chargeAble = [
partial_cost,
fine,
discount,
other_cost
];
$.each(chargeAble, function (chargeIndex, charge) {
charge.blur(function () {
var amount = 0;
for(charge in chargeAble)
if(chargeAble[charge].attr('id') == 'discount')
amount -= (chargeAble[charge].val());
else
amount += (chargeAble[charge].val());
total_cost.val(amount);
});
});
</script>
The code is using a combination of .each() AND a for-in loop... and strangely the callback from a blur() function? It can be simplified like this:
var amount = 0;
$('#bill_amount:disabled, #fine, #discount, #other_cost')
.blur()
.each(function() {
var sign = this.id === 'discount' ? -1 : 1;
amount += parseFloat($(this).val()) * sign;
});
$('#total').val(amount);
Update:
Oh, you want the total to update on blur... try this code:
var $values = $('#bill_amount:disabled, #fine, #discount, #other_cost');
$values.on('blur', function() {
var amount = 0;
$values.each(function(){
var sign = this.id === 'discount' ? -1 : 1;
amount += parseFloat($(this).val()) * sign;
});
$('#total').val(amount);
});
I can see stuff like this all around:
var fine = +$('#fine');
The jQuery() method returns jQuery objects, not numbers or even strings. Forcing a number cast will thus return NaN.
You need to first grab the text inside and than parse numbers of out it. How to do it depends on how your HTML is structured but in general:
In form fields you can normally use .val()
In most other tags you can use .text()
Make sure that all values are interpreted as numbers by JavaScript. Otherwise it will try to calculate some odd result from a string, which might get interpreted as something else than the a decimal number (hex, octa, ...).
You array holds numbers and you act like they are strings
var chargeAble = [ //this holds values
partial_cost,
fine,
discount,
other_cost
];
and in the loop you are using it for an id???
chargeAble[charge].attr('id')

Sum not being calculated properly

The program should do the following: The user should input numbers on the input field on the right and should click compute. The value will be pushed in the array. This will be done X times. At this moment X is hardcoded to 5 but that is not the problem.
The problem is that after the last number is pushed in the array, the sum of the array will be calculated and put out on the webpage. The visualisation isn't a problem and I am pretty sure that the calculations are correct. I think that the problem is how the input is read or inputet in the array. I might be wrong about this though.
One last thing, the function in which everything is calculated is compute1.
EDIT: the actual error: Uncaught TypeError: Cannot read property 'value' of null
This is the entire source code:
<!DOCTYPE HTML>
<head>
<title>Asd</title>
<style>
.btn{
width : 30px;
}
.btn2{
width : 100px;
height : 40px;
}
</style>
</head>
<body>
<center>
<table>
<tr>
<td>Number of elements:</td><td><input type="number" id="textField" class="btn"></input></td>
<td>Please enter a number.</td> <td><input type="number" id="textFiledInp" class="btn"></input></td>
</tr>
</table>
<button class="btn2" onclick="compute1()" >compute</button>
<p id="output"></p>
</center>
</body>
<script>
//var eleNum = parseInt(document.getElementById("textField"));
var eleNum = 5;
var arr = new Array;
function compute1()
{
console.log("hi");
if(eleNum > 0)
{
eleNum--;
arr.push(parseInt(document.getElementById("textFieldInp").value));
console.log(arr[arr.length-1]);
}
else{
var sum = 0;
for(var i = 0; i < arr.size; i++)
{
sum+= arr[i];
}
document.getElementById("output").innerHTML = sum;
}
}
</script>
You have a typo in the id of your element:
id="textFiledInp"
...should be:
id="textFieldInp"
Otherwise getElementById() can't find the element and returns null, hence the error message you quote.
And your for loop is trying to use arr.size but it should be arr.length.
Presetting eleNum to 5 seems a bit strange, but I'm not entirely clear what you're trying to do there so I'm not sure what to advise. I suspect you just need to move the commented out line inside your function and add .value (and uncomment it):
eleNum = parseInt(document.getElementById("textField").value, 10);
And also, never use parseInt() without specifying the radix in the second parameter. This is particularly important for user-entered data. (Because otherwise the browser may interpret a value with a leading 0 as octal, and a leading 0x as hexadecimal.)
After fixing the typos in your HTML, you should change the code to this:
var eleNum = 5;
var arr = []; //see explanation
function compute1(value) {
console.log("hi");
if (eleNum > 0) {
eleNum--;
arr.push(parseInt(document.getElementById("textFieldInp").value || 0, 10)); // see explanation
console.log(arr[arr.length - 1]);
} else {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
document.getElementById("output").innerHTML = sum;
}
}
You were using new Array; instead of new Array(), the better way is to use bracket notation. Or, in your case, you can define an array based on the length given by the user(with the input) or even using yours number of elements. It would be new Array(eleNum).
Why || 0? Because if the input is not defined by the user(value is null) then it sums up 0, otherwise you'll have NaN; remember to specify radix in parseInt, see nnnnnn's answer.
See a working fiddle of this.
You have wrong ID of input:
<td>Please enter a number.</td> <td><input type="number" **id="textFiledInp"** class="btn"></input></td>
and you try to get element of id "textFieldInp":
document.getElementById("textFieldInp").value);
Change id="textFiledInp" to id="textFieldInp" and it should work.
And size is not correct property of javascript array. You should use length property in your loop.
If you want to push in arr the amount of numbers you've declared you should write something like this (I don't know if this is what you want):
function compute1()
{
console.log("hi");
if(eleNum > 0)
{
eleNum--;
arr.push(parseInt(document.getElementById("textFieldInp").value));
console.log(arr[arr.length-1]);
}
else{
var sum = 0;
for(var i = 0; i < arr.length; i++)
{
sum+= arr[i];
}
document.getElementById("output").innerHTML = sum;
}
}
As far as I can tell, your calculations are correct, but you're missing a bracket console.log(arr[arr.length-1)
It should be:
console.log(arr[arr.length-1]);

Using a variable to search an array instead of a static string

Okay, so what I have is basically three dynamic drop down boxes and a 2D array. I have each box adding their values together, and then I want the sum of the values to be searched for through the array to pull out the fifth value on whatever the row the value was on.
var shape = document.getElementById("shape").value;
var dimension_one = document.getElementById("dimension_One").value;
var x = 'x';
var dimension_two = document.getElementById("dimension_Two").value;
var selected_beam = shape + dimension_one + x + dimension_two; // combine all values from text boxes
alert(selected_beam);
for (i = 0; i < array_shapes.length; i++)
{
if (array_shapes[i][2] == selected_beam) {
alert('Area=' + array_shapes[i][5]);
//Area= array_shapes[i][5]);
}
}
I know that selected _beam is giving me the value I want, and I also know that the array loop returns what I want out of the array but only if I replace
if (array_shapes[i][2] == selected_beam)
with
if (array_shapes[i][2] == "value I want to search for")
So what I really need to know is - why will it only accept it as a string and not as my selected_beam variable.
Based on your array values, it looks like you need var x to be uppercase like:
var x = 'X';
If I am reading your array correctly, it also looks like the beam size is in element 0 and 1 of the array not 1 and 2, so you may need to not look for array_shapes[i][2], but rather array_shapes[i][0] or array_shapes[i][1]
The first item in the array is at index value = 0.
You need to do some debugging.
To start off, you need to know why selected_beam !== "your value".
I suggest you use this function to compare the strings:
function compare( s1, s2 ){
alert("s1: " + s1.toString());
alert("s2: " + s2.toString());
if (s1.toString() == s2.toString())
return alert("true");
return alert("false");
}
>>> compare(selected_beam,"your value");
The problem might be as simple as having unnecessary characters in your selected_beam.
So where you have alert(selected_beam), try to compare the strings and see if it returns true or false.
You are concatenating values that you're parsing from a text box. The result will be a string
Try doing:
var selected_beam = parseInt(shape) + parseInt(dimension_one) + parseInt(x) + parseInt(dimension_two);

Categories

Resources