Jquery array querying not working - javascript

So I have to pares through an array and it's multiple variables and input them on separate lines.
Here is the code:
while (array[x] != null) {
y = 0;
y = x;
alert(y + 'y');
setTimeout(function() {
if (y == 0 || y % 3 === 0) {
var namestring = array[y];
var namestring = namestring.replace('[','');
var namestring = namestring.replace('[','');
var namestring= namestring.replace('"', '');
var namestring= namestring.replace('"', '');
}
if (y % 2 != 0 || y % 3 != 0 && x > 0) {
var date = array[y]
var date = date.replace('"', '');
var date = date.replace('"', '');
}
if (x % 2 == 0 && x > 0) {
var text = array[y];
var text = text.replace('"', '');
var text = text.replace('"', '');
var text = text.replace("]", '');
var text = text.replace("]", '');
createcard(namestring,date,text);
}
}, 500);
if (x > 500) {
break;
};
x++;
alert(x + 'x');
}
The alerts are simply for debugging. Anyway, my variables, for example namestring gets returned as undefined. However, if I change the line to say array[0] instead of array[y], it works, even if y is set to 0...

You're assigning
y = 0;
and
y = x;
x appears to be undefined in that code snippet but maybe it is part of a larger batch of code. It basically looks like you're overwriting y with the value of x?

Related

closest number, based on two numbers

Im currently checking what the closest number would be compared to an array:
var testarray1 = [4054,4938,4983,1928,8833];
var test = 5000;
var result = testarray1.reduce(function(prev, curr) {
return (Math.abs(curr - postcode) < Math.abs(prev - postcode) ? curr : prev);
}
This works fine.
but when i have it like multi numbers in one, it dosent work:
var testarray1 = ["4000-5595","4400-4720"];
var test = 4630;
for (var x =0; x < testarray1.length; x++) {
var selectedPostcode = testarray1[x][0];
var splitted = selectedPostcode.split("-");
var from = parseInt(splitted[0]);
var to = parseInt(splitted[1]);
if (postcode >= from && postcode <= to) {
return selectedPostcode;
break;
}
}
in the example code above, it would return "4000-5595", but how can i do so it selects the closest one, in this case it would be the "4400-4720"?
Try like below. Explanation is in comments.
var testarray1 = ["4000-5595", "4400-4720"];
var postcode = 4630;
// Take two variables to set difference and result
// set difference default value to -1
var difference = -1;
var result = "";
for (var x = 0; x < testarray1.length; x++) {
// use testarray1[x] instead of testarray1[x][0]
var selectedPostcode = testarray1[x];
var splitted = selectedPostcode.split("-");
var from = parseInt(splitted[0]);
var to = parseInt(splitted[1]);
if (postcode >= from && postcode <= to) {
// get difference
let currDiff = Math.abs(postcode - from) + Math.abs(postcode - to);
// difference = -1 means there is no existing value so set current as result
// check current difference is less than existing one.
if (difference == -1 || currDiff < difference) {
difference = currDiff;
result = selectedPostcode;
}
}
}
console.log(result);
If you want closest value based on minimum difference from either one of the value then use let currDiff = Math.min(Math.abs(postcode - from), Math.abs(postcode - to));.
var testarray1 = ["4000-5595", "4400-4720", '4800-5000'];
var postcode = 4630;
// Take two variables to set difference and result
// set difference default value to -1
var difference = -1;
var result = "";
for (var x = 0; x < testarray1.length; x++) {
// use testarray1[x] instead of testarray1[x][0]
var selectedPostcode = testarray1[x];
var splitted = selectedPostcode.split("-");
var from = parseInt(splitted[0]);
var to = parseInt(splitted[1]);
if (postcode >= from && postcode <= to) {
// get difference
let currDiff = Math.min(Math.abs(postcode - from), Math.abs(postcode - to));
// difference = -1 means there is no existing value so set current as result
// check current difference is less than existing one.
if (difference == -1 || currDiff < difference) {
difference = currDiff;
result = selectedPostcode;
}
}
}
console.log(result);
You have to check for every interval and check if previous ans is closet or current interval is closet and change ans accordingly like this.
var testarray1 = ['4000-5595', '4400-4720']
var test = 4630
let ans
for (var x = 0; x < testarray1.length; x++) {
var selectedPostcode = testarray1[x]
var splitted = selectedPostcode.split('-')
var from = parseInt(splitted[0])
var to = parseInt(splitted[1])
if (ans) {
if (ans[0] < from || ans[1] > to) ans = [from, to]
} else {
if (test >= from && test <= to) {
ans = [from, to]
}
}
}
console.log(ans.join('-'))

Can't make the code recognize 0 as a value

I'm making an editable RPG sheet. For this specific section, I need it to compare the 1_7, 2_7 and 3_7 to the result of the equation, and have it select the smaller value. However, while it works on most situations, it doesn't recognize 0 as a value. 1_7, 2_7 and 3_7 are inputted manually.
What should I do in order to get the code to recognize 0 as a value?
var x =
this.getField("1_7").value;
var y =
this.getField("2_7").value;
var z =
this.getField("3_7").value;
var f = Math.floor((this.getField("Des Temp").value - 10) / 2);
var temp;
if(!x)
{
x = f;
}
if(!y)
{
y = f;
}
if(!z)
{
z = f;
}
if(x <= y && x <= z)
temp = x;
else if(y <= z)
temp = y;
else
temp = z;
if(f > temp)
f = temp;
if(f > 0){
event.value = "+" + f;
}
else{
event.value = f;
}
O is a "falsy" value so
if(!x)
Is doing what it is supposed to do. The empty value is probably an empty string so you could do
if ( ! x.length )
instead.
$('#x').on( 'input', function() {
console.log( ! $(this).val().length );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id='x' >
It's because 0 is considered as false inside a javascript comparaison. If you want to verify if the field have data, you can use the length property.
var x = 0;
var y = 5;
var z = 3;
var f = 10;
if(0)
{
console.log("0 is false");
}
if(1)
{
console.log("1 or any number != 0 is true");
}
if(x.length)
{
x = f;
console.log("x is not set");
}
if(y.length)
{
y = f;
console.log("y is not set");
}
if(y.length)
{
z = f;
console.log("z is not set");
}

Combining change and keyup

I have a form in which I am calculating cost for a product. It depends on both an input value they put in and a select they choose.
Is there a way to combine the change and keyup events into one cleaner segment?
My code is as followed:
https://jsfiddle.net/qrv57qtu/
$('#input').keyup(function(){
var x = $('#input').val();
var y = $('#select').val();
if (y == '5') {
var z = 5;
}
else if (y == '10') {
var z = 10;
}
var z = x * y;
$('#total').html(z);
});
$('#select').change(function(){
var x = $(this).val();
var y = $('#input').val();
if (x == '5') {
var z = 5;
}
else if (x == '10') {
var z = 10;
}
var a = y * z;
$('#total').html(a);
});
Thank you.
You can use a single comma-delimited selector to get both elements. Then if you use the on() method you can provide a space-delimited string containing the event names you want to bind to, like this:
$('#input, #select').on('keyup change', function() {
var x = $('#input').val();
var y = $('#select').val();
if (y == '5') {
var z = 5;
}
else if (y == '10') {
var z = 10;
}
var z = x * y;
$('#total').html(z);
});
Also note that the if condition in your logic is entirely redundant as you overwrite the value of z at the end anyway
Here's the working code:
$(document).on("keyup change", "#input, #select", function(){
var x = $('#select').val();
var y = $('#input').val();
if (x == '5') {
var z = 5;
}
else if (x == '10') {
var z = 10;
}
var a = y * z;
$('#total').html(a);})
https://jsfiddle.net/itsrikin/gaL237qg/

A while loop to add the digits of a multi-digit number together? (Javascript)

I need to add the digits of a number together (e.g. 21 is 2+1) so that the number is reduced to only one digit (3). I figured out how to do that part.
However,
1) I may need to call the function more than once on the same variable (e.g. 99 is 9+9 = 18, which is still >= 10) and
2) I need to exclude the numbers 11 and 22 from this function's ambit.
Where am I going wrong below?
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i];
};
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
};
} else {
xResult = x;
};
console.log(xResult);
//repeat while loop for y and z
Here are the problems with your code
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var proc = num.toString().split("");
var total = 0;
for (var i=0; i<proc.length; i++) {
total += +proc[i]; // indentation want awry
}; // don't need this ; - not a show stopper
// you're not returning anything!!!!
};
while(x > 9 && x != 11 && x != 22) {
numberMagic(x);
}; // ; not needed
// because x never changes, the above while loop would go on forever
} else { // this else has no if
xResult = x; // even if code was right, x remains unchanged
};
console.log(xResult);
Hope that helps in some way
Now - here's a solution that works
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
while (num > 9) {
if (num == 11 || num == 22) {
return num;
}
var proc = num.toString().split("");
num = proc.reduce(function(previousInt, thisValueString) {
return previousInt + parseInt(thisValueString);
}, 0);
}
return num;
}
console.log(numberMagic(x));
console.log(numberMagic(y));
console.log(numberMagic(z));
I'm not sure to understand what you want..
with this function you reduce any number to one single digit
while(num > 9){
if(num == 11 || num == 22) return;
var proc = num.toString();
var sum = 0;
for(var i=0; i<proc.length; i++) {
sum += parseInt(proc[i]);
}
num = sum;
}
is it what you are looking at?
I wrote an example at Jsfiddle that you can turn any given number into a single digit:
Example input: 551
array of [5, 5, 1] - add last 2 digits
array of [5, 6] - add last 2 digits
array of [1, 1] - add last 2 digits
array of [2] - output
Here is the actual code:
var number = 1768;
var newNumber = convertToOneDigit(number);
console.log("New Number: " + newNumber);
function convertToOneDigit(number) {
var stringNumber = number.toString();
var stringNumberArray = stringNumber.split("");
var stringNumberLength = stringNumberArray.length;
var tmp;
var tmp2;
var tmp3;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
while (stringNumberLength > 1) {
tmp = parseInt(stringNumberArray[stringNumberLength - 1]) + parseInt(stringNumberArray[stringNumberLength - 2]);
stringNumberArray.pop();
stringNumberArray.pop();
tmp2 = tmp.toString();
if (tmp2.length > 1) {
tmp3 = tmp2.split("");
for (var i = 0; i < tmp3.length; i++) {
stringNumberArray.push(tmp3[i]);
}
} else {
stringNumberArray.push(tmp2);
}
stringNumberLength = stringNumberArray.length;
console.log("Array: " + stringNumberArray);
console.log("Array Length: " + stringNumberLength);
}
return stringNumberArray[0];
}
function addDigits(n) {
let str = n.toString().split('');
let len = str.length;
let add,
acc = 0;
for (i=0; i<=len-1; i++) {
acc += Number(str[i]);
}
return acc;
}
console.log( addDigits(123456789) ); //Output: 45
Just make it a While loop, remember a While loops it's just the same as a For loop, only you add the counter variable at the end of the code, the same way you can do with a Do{code}while(condition) Only need to add a counter variable at the end and its gonna be the same. Only that the variable its global to the loop, I mean comes from the outside.
Ej.
let i = 0; //it's global to the loop, ( wider scope )
while (i<=x) {
//Code line;
//Code line;
//Code line;
//Code line;
i++
}
Now this is working with an outside variable and it's NOT recommended.. unless that var its local to a Function.
Please look at the this solution also
var x = 123;
var y = 456;
var z = 789;
var numberMagic = function (num) {
var total = 0;
while (num != 0) {
total += num % 10;
num = parseInt(num / 10);
}
console.log(total);
if (total > 9)
numberMagic(total);
else
return total;
}
//Call first time function
numberMagic(z);

How to get the elements surrounding a selected element in a matrix

I have a 3x3 matrix and when I select a element in this matrix, I need to find elements surrounding that element(i.e.top, left, right, bottom).
Below is the code I used to create a 3x3 matrix -
You can view this
// declare array of multi dimensions
var arrOfArr = new Array(3);
// or declare as [[],[],[]] as suggested by Elijah
// allocate storage
for (var x = 0; x < arrOfArr.length; x++) {
arrOfArr[x] = new Array(3);
}
// Populate the array
// first array
arrOfArr[0][0] = "00";
arrOfArr[0][1] = "01";
arrOfArr[0][2] = "02";
// second array
arrOfArr[1][0] = "10";
arrOfArr[1][1] = "11";
arrOfArr[1][2] = "12";
// third array
arrOfArr[2][0] = "20";
arrOfArr[2][1] = "21";
arrOfArr[2][2] = "22";
alert(arrOfArr);
If I select an element in this matrix, I need to get top,left,right and bottom element of the selected element. How can I do this
This function will give you an object representing the elements around the selected element at x, y in the matrix matrix:
function getSurroundingElements(x, y, matrix) {
var x_limit = matrix.length;
if (x_limit == 0) return null; //matrix is empty
var y_limit = matrix[0].length; //Assumes all rows in the matrix are of same length (otherwise, not a matrix, right?)
return {
'tl':((x-1 >= 0 && y-1 >= 0)?matrix[x-1][y-1]:null),
'tc':((y-1 >= 0)?matrix[x][y-1]:null),
'tr':((x+1 < x_limit && y-1 >= 0)?matrix[x+1][y-1]:null),
'ml':((x-1 >= 0)?matrix[x-1][y]:null),
'mr':((x+1 < x_limit)?matrix[x+1][y]:null),
'bl':((x-1 >= 0 && y+1 < y_limit)?matrix[x-1][y+1]:null),
'bc':((y+1 < y_limit)?matrix[x][y+1]:null),
'br':((x+1 < x_limit && y+1 < y_limit)?matrix[x+1][y+1]:null)
};
}
NOTE: null is returned if the matrix is empty and null is the value set for illegal values (i.e. edge cases) - Thanks to Troy Gizzi for pointing out a complete solution.
This function will return a object contains four value, the value in the edge will return undefined.
var MAXTRIX_LENGTH = 3;
function select(x, y) {
var maxIndex = MAXTRIX_LENGTH - 1;
if (x >= 0 && x <= maxIndex && y >= 0 && y <= maxIndex) {
return {
"top": y > 0 ? arrOfArr[x - 1][y] : undefined,
"bottom": y < maxIndex ? arrOfArr[x + 1][y] : undefined,
"left": x > 0 ? arrOfArr[x][y - 1] : undefined,
"right": x < maxIndex ? arrOfArr[x][y + 1] : undefined
};
} else {
return undefined;
}
}
var result = select(0, 1);
if (result == undefined) {
alert("Index over range.")
} else {
alert("top: " + result.top + " bottom: " + result.bottom + " left: " + result.left + " right: " + result.right);
}
Please chech my fiddle. DEMO
var arrOfArr = new Array(3);
for (var x = 0; x < arrOfArr.length; x++) {
arrOfArr[x] = new Array(3);
}
arrOfArr[0][0] = "450";
arrOfArr[0][1] = "212";
arrOfArr[0][2] = "102";
// second array
arrOfArr[1][0] = "120";
arrOfArr[1][1] = "1211";
arrOfArr[1][2] = "1112";
// third array
arrOfArr[2][0] = "220";
arrOfArr[2][1] = "2121";
arrOfArr[2][2] = "2222";
$("input[type=submit]").click(function (){
var selectedVal=($("input[type=text]").val());
var result="Element not found in matrix";
//alert( arrOfArr[2][0]==selectedVal);
($.each(arrOfArr,function(index,value){
$.each(value,function(subIndex,subVal){
if(selectedVal==subVal){
var leftval = checkNoElement(arrOfArr, index, subIndex-1);
var rightval=checkNoElement(arrOfArr, index,subIndex+1);
var upperVal=checkNoElement(arrOfArr, index-1, subIndex);
var lowerVal=checkNoElement(arrOfArr,index+1, subIndex);
result=(" Left:"+leftval+ " \n right:" + rightval + " \n Upper:" + upperVal + " \n Lower:" + lowerVal);
}
});
}));
alert(result)
});
function checkNoElement(element,index1,index2){
var firstChk=element[index1]== undefined ? undefined :"";
if(firstChk==undefined){
return "no element"
}else{
return (element[index1][index2]== undefined ? "no element":element[index1][index2]);
}
}

Categories

Resources