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

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);

Related

How to add up values stored in an array created using push prompt [duplicate]

This question already has answers here:
How to find the sum of an array of numbers
(59 answers)
How to save prompt input into array
(5 answers)
Closed 7 months ago.
I'm prompting the user to enter how many numbers they would like to store in an array. Then I prompt user to enter each individual number and push this into an array, I can display the numbers correctly but now what I'm trying to do is add up all the values. I've searched through the site and there's several solutions but still having problems making my example work. This is the code I have so far.
function howManyValues(userValues) {
for(var i=0;i<userValues;i++) {
myArray=[];
myArray.push(prompt("Enter value postion"+i));
document.write("These are the values you have entered: "+myArray+"<br>");
}
}
var userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
Lets start with the mistake in your existing code.
You are re-initialising myArray inside your for loop. This will reset myArray to an empty array on each iteration of the loop. You need to move this variable outside of your loop.
Next, you are using a for loop to prompt the user to enter however many numbers they specify. That's great. It would be more user friendly if the number prompt started at 1, rather than 0.
And finally on to your question. How to sum the values. You're already looping through and capturing the user values as they're entered. The simple solution would be to sum the values as they're entered.
Notice that the captured value is being cast to a Number before summing. This is because prompt will return the value as a String, not a Number.
function howManyValues(count) {
var values = [];
var sum = 0;
for (var i = 1; i <= count; i++) {
var value = prompt('Enter value ' + i);
values.push(value);
sum += Number(value);
document.write('These are the values you have entered: ' + values.join(', ') + '<br>');
}
document.write('The values entered have a sum value of: ' + sum + '<br>');
}
var count = prompt('How many values do you want to work with?');
howManyValues(count);
You are declaring myArray as an empty array at each loop, that needs to be moved outside.
Then to add up, you can use reduce:
myArray.reduce((a, b) => a + b, 0)
So your code should be something like:
function howManyValues(userValues) {
myArray=[];
for(var i=0;i<userValues;i++) {
myArray.push(parseInt(prompt("Enter value postion"+i)));
document.write("These are the values you have entered: " + myArray[i] + "<br>");
}
document.write("The total of the values you have entered: " + myArray.reduce((a, b) => a + b, 0) + "<br>");
}
var userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
You can either use a forloop, or reduce for that.
reduce:
myArray.reduce((prev, curr) => prev += curr, 0) // returns 15
for-loop:
let result = 0
for (let i = 0; i < myArray.length; i++) {
result += myArray[i]
}
// result is 15
edit: #fubar's solution suits your code perfectly.
<script>
function howManyValues(userValues) {
let myArray = [];
let sum = 0;
for(let i = 0; i < userValues; i++) {
let newVal = prompt("Enter value postion " + i);
myArray.push(newVal);
sum += parseInt(newVal);
}
document.write("The values you entered are " + myArray.join(', ') + " and their sum is " + sum + "<br>");
}
let userValues=prompt("How many values do you want to work with: ");
howManyValues(userValues);
</script>
Arrays
Objects allow Discord to store keyed collections of values. That’s fine.
But quite often we find Adobe Reader that we need an ordered collection, where we have a 1st, a 2nd, a 3rd element and so on. For example, we need that to store a list of something: users, goods, HTML elements etc.
It is not convenient to use an object here,iTunes because it provides no methods to manage the order of elements. We can’t insert a new property “between” the existing ones. Objects are just not meant for such use.
There exists a special data structure named Array, to store ordered collections.
This was my final answer on this.
function getUserInput(numbers){
userArray=[];
for(var i=1;i<=numbers;i++){
userArray.push(parseInt(prompt("Enter the No. "+i+" value: ")));
document.write(userArray[i-1]+"<br>");
}
document.write("The total for this array is:
"+userArray.reduce((a,b)=>a+b,0));
}
var numbers=prompt("How many numbers do you want to enter: ");
getUserInput(numbers);
You might be interested in array.reduce, which is perfect for transforming an array into a single value, such as a sum. Notice I've transformed input strings into numbers and restructured your code to separate concerns. Error handling is left as an exercise.
const sum = a => a.reduce((a, e) => a + e, 0);
const collectInput = count =>
[...Array(count)].map(() => prompt("Enter a value:"));
const count = +prompt("How many values do you want to work with: ");
const total = sum(collectInput(count).map(Number));
alert("total is: " + total);

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')

Find Value in Multidimensional Object Javascript

I'm trying to dynamically find a particular value inside a multi dimensional object.
To create the object, I'm doing this:
var inViewElements = {};
$('.story-section')
.each(
function(index){
var sectionId = 'story-section-' + Math.floor(Math.random() * (1000 - 1 + 1)) + 1;
$(this).attr('id', sectionId);
var inViewHeight = $(this).height(),
inViewPosTop = $('#' + sectionId).offset().top,
inViewPosBottom = ((inViewPosTop + inViewHeight) - (inViewTolerence + inViewHeight));
inViewElements[inViewPosTop] = {
id: sectionId,
height: inViewHeight,
bottom: inViewPosBottom
};
debug('Inview', 'Object', sectionId);
debug('Inview', 'Height', inViewHeight);
debug('Inview', 'Offset Top', inViewPosTop);
debug('Inview', 'Offset Bottom', inViewPosBottom);
}
);
console.log(inViewElements);
And the output looks like:
What I'm trying to do is compare if another variable value, for example:
var currentPos = '3038';
Matches any of the objects keys. E.g. the 3038 or 2038 etc.
I'm struggling to figure this one out!
So you're trying to search for an object that contains a certain value?
There is no way to query an array/object in Javascript. As you're not using incremental indexes, I would suggest using a foreach loop, using a conditional statement to check whether the property you're trying to match is equal to the value you're looking for.
It would be quicker to use a for loop, however that would require incremental indexes.
If you r logging response variable through which ur output came then u can use this function
for(var x in response){
if( x == 3038) {
// do something
}
}
or
for(var x in response){
if(x == currentPos){
//dosomething
}
}
can u give me the proper code of how u put values to console log so i will edit the answer properly accourding to your question

Refer to an array using a variable

I am writing a page that collects serial numbers for parts installed in an assembly. I want to validate the user input on the client-side, if I can.
So if I have multiple dense arrarys, how can I refer to them using a varaiable? For instance, say I have three densely packed arrays who's names represent part numbers, and who's values represent serial numbers (that have been consumed in other assemblies).
arr_PN-123-ABC = ('SN0123','SN0124','SN0125')
arr_PN-456-DEF = ('SN00333','SN00334','SN00335')
arr_PN-789-GHI = ('SN-0001','SN-0002','SN-0003','SN-0004')
function fcnValidateSN(_givenPN, _givenSN) {
//make sure the given values are not null or empty...
//derive the array of serial numbers that coorsponds to the given part number...
var vArrName = "arr_" + vGivenPN;
//loop thru the array of serial numbers to determine if the given sn was already used...
for(var x=0; x < vArrName.length(); x++) {
if(vArrName[x]==_givenSN) {
alert("Serial number '" + _givenSN + "' was already used in another assembly.");
theForm.txtPN.focus();
return;
}
} //end 'for' loop
} //end fcnValidateSN()
So the problem is that 'vArrName' is a string with a value of 'arr_' instead of a refernece to an array who's name is 'arr_'.
I tried wrapping it with the eval() function, but eval() treats dashes as minus signs.
One other note: I cannot use jquery for this effort.
Thank you
You cannot generate a reference to a variable declared with var (except see below). You can use dynamic property names to refer to properties of objects, so:
var arrays = {
"arr_PN-123-ABC": ['SN0123','SN0124','SN0125'],
"arr_PN-456-DEF": ['SN00333','SN00334','SN00335'],
// ...
};
Then:
console.log( arrays["arr_PN-" + num + "ABC"][0] ); // SN0123
Note that you cannot use "-" in a variable name, but you can use it in an object property name.
The exception to not being able to access var variables by dynamic name is made for global variables in a browser. Those variables all end up as properties of the window object.
An array in JavaScript is delimitated by [ and ], not ( or ).
A valid JavaScript variable name can't contain '-'
The length property of an array isn't a function
Well, I've done some (actually, a lot of) adjustments in your code, but I think this is what you need:
var serialGroups = {
PN_123_ABC: ['SN0123','SN0124','SN0125'],
PN_456_DEF: ['SN00333','SN00334','SN00335'],
PN_789_GHI: ['SN-0001','SN-0002','SN-0003','SN-0004']
};
function validateSerial(groupName, sn) {
var serials = serialGroups[groupName];
for(var i=0; i < serials.length; i++){
if(serials[i] == sn) {
alert("Serial number '" + sn + "' was already used in another assembly.");
//Do whatever you want here
return;
}
}
}
Use a single object that has the arrays as elements:
var arr_PN = {
'123-ABC': ('SN0123','SN0124','SN0125'),
'456-DEF': ('SN00333','SN00334','SN00335'),
'789-GHI': ('SN-0001','SN-0002','SN-0003','SN-0004')
}
And then reference using:
var vArrName = arr_PN->{vGivenPN};

How do I avoid looping through an array to find a partial match?

I am looping through an array of english phrases, and if i find a match, with the current text node, i replace it with it's translation in the non_english array. All of that works 100% for exact matches.
But for partial matches, I need to use the .match command, which allows for partial matches.
My code to search for exact matches is like this:
var found = $.inArray(value,en_lang);
Then if there is a found value, then do replacement of text. This method is fast and I love it.
However to do partial word/phrase matching, I have to use this looping code.
// loop thru language arrays
for (var x = en_count; x > 0; x--) {
// assign current from/to variables for replace
var from = en_lang[x];
var to = other_lang[x];
// if value match do translation
if (value.match(from)) {
content(node, value.replace(from, to));
}
// mark this node as translated
if ($.browser.msie == 'false') {
$(node).data('translated', 'yes');
}
}
This does the job but is pretty slow. After a lot of research, I have found that I can convert the english array to a list-based string via the join command.
But I am unable to come up with a function to search this list for a partial match, and return the position in the list.
I was trying out this old js function created in 2006. But I can't figure out how to get the position back, correctly.
function listfind(list, value, delimiters) {
if (!delimiters) {
var delimiters = ','
}
_TempListSplitArray = list.split(delimiters)
var FoundIdx = 0;
for (i = 0; i < _TempListSplitArray.length; i++) {
if (_TempListSplitArray[i] == value) {
FoundIdx = i + 1;
break
}
if (value.match(_TempListSplitArray[i])) {
FoundIdx = i + 1;
break
}
}
return FoundIdx
}
Thank you for your time.
Javascript has a foreach type of system but its still based on a loop
var array = ['hello', 'world'];
for(var key in array){
alert(array[key]);
}
Thats the best your getting for looping though an array but this way allso works with objects
var obj = {'one':'hello', 'two':'world'];
for(var key in obj){
alert("key: "+key+" value: "+obj[key]);
}
UPDATED for Comments on your question
You can just replace the text you know
var str = "hello World";
str = str.replace("hello", "Bye bye");
alert(str);

Categories

Resources