Iteratively Transform a data value - javascript

This is an extremely beginner question, but i have a value that i want to transform multiple times, each time taking the output from the previous result as input.
Lets say i want to iterate through an array of characters [a,6,b,4] and append each of them the word brownbear. The final output that i would want is brownbeara6b4. Also, I'm not looking for a solution that just dumps the context of the array and concatenates it to the word. I need something that can iteratively transform data, no matter what the use case is.
To maybe provide another example, i want to run a function x amount of times on some value. Each time I want to take the output of the function and use it as input for the next time the function is ran.
How would i solve this using JS?

Maybe you are looking for a recursive function that runs X times. In that case, this can be helpful.
Basically what I'm doing here is to call the same function with the transformed data of each iteration over and over until i reach X amount of times.
var my_array = ["a", "1", "b", "2"]
var times = 2
function iterative_function(data, times_to_be_run = 1){
if(times_to_be_run > 0){
var transformed_data = data.map(a=> a + " hello")
return iterative_function(transformed_data, times_to_be_run - 1)
}else{
return data
}
}
console.log(
iterative_function(my_array, times)
)

Related

getting new nth indexed number of element from an array according to the given nth element in a circular manner

so the problem is simple . here i want to return the new nth element of an array according to the
previous nth element sent by the user.for example
['1','3','5','7','9','11']
if a user sends a value of 3 then I would like to return 7, if the user sends 5 then I would like to return 9 , if they send 7 then 11 and when they send 11 then I want to return 3. basically its like puting the array in a circular mode and return the next element.
here is my code.
var indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
var index=indices.indexOf(uservalue);
return indices[index+index_to_add];
everything here works fine but when the array finishes or nears the end then I get undefined instead of element from the first. how can i get the element from the beginning if the element index is undefined or the array finishes?
Using the Modulo operator:
return indices[(index+index_to_add) % indices.length];
Note: this will only handle the case when uservalue is actually part of the array. You might want to add a clause like if(index === -1) return 'Uservalue not in array.' or throw an error.
If I've interpreted your question correctly, a solution would be to encapsulate the processing within a recursive function, if you're after readable code and are unfamiliar with the Modulo function (doing it this way also makes it easier to change the process in the future):
const indices=['1','3','5','7','9','11'];
var index_to_add=2;
var uservalue='1';/// will be sent by the user
console.log(GetElemAtIndex(GetIndex(userValue) + index_to_add));
function GetIndex(userValue) {
return indices.indexOf(userValue); // If this is -1 the user has entered something not in the array
}
function GetElemAtIndex(toFind) {
if (indices.length > toFind) {
return indices[toFind];
}
else {
return GetElemAtIndex(toFind - indices.toLength);
}
}
The modulo function in Taxel's answer is a more efficient way of doing the GetElemAtIndex block.

How to NOT select this but anything else in Regexr?

I have this string made up for a TMS program... I later found out I want the program to NOT select these postalcodes, it's now matching the string. I want it to be able to select anything between 1000-10000\s*a-zA-Z except for this:
(8388|8389|8390|8391|8392|8393|8394|8395|8396|8397|8398|8400|8401|8403|8404|8405|8406|8407|8408|8409|8410|8411|8412|8413|8414|8415|8420|8421|8422|8423|8424|8425|8426|8427|8428|8430|8431|8432|8433|8434|8435|8440|8441|8442|8443|8444|8445|8446|8447|8448|8449|8451|8452|8453|8454|8455|8456|8457|8458|8459|8461|8462|8463|8464|8465|8466|8467|8468|8469|8470|8471|8472|8474|8475|8476|8477|8478|8479|8481|8482|8483|8484|8485|8486|8487|8488|8489|8490|8491|8493|8494|8495|8497|8500|8501|8502|8503|8505|8506|8507|8508|8511|8512|8513|8514|8515|8516|8517|8520|8521|8522|8523|8524|8525|8526|8527|8528|8529|8530|8531|8532|8534|8535|8536|8537|8538|8539|8541|8542|8550|8551|8552|8553|8554|8556|8560|8561|8563|8564|8565|8566|8567|8571|8572|8573|8574|8581|8582|8583|8584|8600|8601|8602|8603|8604|8605|8606|8607|8608|8611|8612|8613|8614|8615|8616|8617|8618|8620|8621|8622|8623|8624|8625|8626|8627|8628|8629|8631|8632|8633|8635|8636|8637|8641|8642|8644|8647|8650|8651|8658|8700|8701|8702|8710|8711|8713|8715|8721|8722|8723|8724|8730|8731|8732|8733|8734|8735|8736|8737|8741|8742|8743|8744|8745|8746|8747|8748|8749|8751|8752|8753|8754|8755|8756|8757|8758|8759|8761|8762|8763|8764|8765|8766|8771|8772|8773|8774|8775|8800|8801|8802|8804|8805|8806|8807|8808|8809|8811|8812|8813|8814|8816|8821|8822|8823|8830|8831|8832|8833|8834|8835|8841|8842|8843|8844|8845|8850|8851|8852|8853|8854|8855|8856|8857|8860|8861|8862|8871|8872|8880|8881|8882|8883|8884|8885|8890|8891|8892|8893|8894|8895|8896|8897|8899|8900|8901|8902|8903|8911|8912|8913|8914|8915|8916|8917|8918|8919|8921|8922|8923|8924|8925|8926|8927|8931|8932|8933|8934|8935|8936|8937|8938|8939|8941|9001|9003|9004|9005|9006|9007|9008|9009|9011|9012|9013|9014|9021|9022|9023|9024|9025|9026|9027|9031|9032|9033|9034|9035|9036|9037|9038|9040|9041|9043|9044|9045|9047|9050|9051|9053|9054|9055|9056|9057|9060|9061|9062|9063|9064|9067|9071|9072|9073|9074|9075|9076|9077|9078|9079|9081|9082|9083|9084|9086|9087|9088|9089|9091|9100|9101|9102|9103|9104|9105|9106|9107|9108|9109|9111|9112|9113|9114|9121|9122|9123|9124|9125|9131|9132|9133|9134|9135|9136|9137|9138|9141|9142|91439144|9145|9146|9147|9148|9150|9151|9152|9153|9154|9155|9156|9160|9161|9162|9163|9164|9166|9171|9172|9173|9174|9175|9176|9177|9178|9200|9201|9202|9203|9204|9205|9206|9207|9211|9212|9213|9214|9215|9216|9217|9218|9219|9221|9222|9223|9230|9231|9233|9240|9241|9243|9244|9245|9246|9247|9248|9249|9250|9251|9254|9255|9256|9257|9258|9260|9261|9262|9263|9264|9265|9269|9270|9271|9280|9281|9283|9284|9285|9286|9287|9288|9289|9290|9291|9292|9293|9294|9295|9296|9297|9298|9299|9851|9852|9853|9871|9872|9873|9950)\s*[a-zA-Z]{2}
I obviously tried the [^] function and the ?: function but I can't get it working properly.
Just break this string into a set(I think slice function can do that) then sort it and every time you get a value match if it exists in this set or not.
Lets make it easier, I am guessing you are getting numbers in string format of some sort with some form of separation in this case "|".
Step one create array by splinting string based on separator
Step two use filter function that will return a new array based on conditions you provide as shown in example.
Below example takes into consideration edge cases e.g. we are only comparing numbers alphabets are of lesser comparative value to us. What we have to make sure is any comparative value starts with number rest is is all gibberish. So extract number and run bit of magic on that.
Your sting was too long I have used a hypothetical scenario to give you what you want. Rest should be self explanatory in example.
data = '100|999|1000|s1000|10d00|1000f|2500|7500|10000|10001|10500';
dataArray = data.split("|");
dataFiltered = dataArray.filter(function (item) {
extractedNumber = item.match(/^\d+/g);
if(extractedNumber > 999 && extractedNumber <10001) {
return item;
}})
console.log(dataFiltered)
to check on whats being extracted run following and update function as needed.
data = '100|999|1000|s1000|10d00|1000f|2500|7500|10000|10001|10500';
dataArray = data.split("|");
dataFiltered = dataArray.filter(function (item) {
extractedNumber = item.match(/^\d+/);
console.log(extractedNumber);
if(extractedNumber > 999 && extractedNumber <10001) {
return item;
}})
console.log(dataFiltered)

Finding the value of an array?

I am coding a sequencer that allows you to choose which sound you want to be carried into different parts of the code. I am using an array that holds the sound ID value and if a different sound is selected, the array is reset and the value changes. Initially, I thought using this snippet would work to check what sound has been chosen:
if(sounds == 1){
//insert effect of sound value
}
But, this did nothing. I then tried:
sounds == [1];
but that had no effect at all. What code should be used when trying to execute code based on the value of an array with a single item (if that makes sense)?
Firstly, by writing sounds == 1 you are checking if the size of "sounds" array is 1 or not.
To access the value of the array element itself use:
sounds[0] == n
Count in array starts from 0, and last element will be length of array sounds.length - 1
Now, if I correctly understood your question itself and you want to output certain sound based on which element is chosen from array, then you could use Switch / Case. First iterate through array using for loop. Then declare Switch() expression. Then, write what kind of output / action should happen when case happens.
for (int i = 0; i < values.length; i++) {
Switch (sounds[i]) {
case 1: // imagine sound ID is 1
//output code // this code will get executed
break;
case 2: // sound ID is 2
//output code // this code will get executed
break;
case 3: // sound ID is 2
//output code // this code will get executed
break;
}
}
As far as I understand your concern, You want to check the value inside the array right?
In that way, You can check the values of the array by using includes() method.
Like:
sounds = [1,2,3,4,5,6];
if(sounds.includes(1)) {
//insert effect of sound value
} else {
// Do else thing here.
}
This might resolve your issue.
Based on our question, you are saying you have an array of sound values. I imagine it looks like
var sounds = ["1"]
If this is the case, you can do sounds.includes("1") to see it "1" is present.

difficulty with adding values from html textbox in javascript

Sorry if this is a stupid question. I am a newbie to programming...
I have 3 values from a text input. I want 2 of these values to be stored into separate arrays for later access. finally I want to display a sum of these 3 values in my document.
What am I doing wrong?
Here is my code:
<script>
function displayCurrentBalance() {
var initialBalance = parseFloat(document.getElementById("initialBalance").value);
var inAmounts=[0];
var outAmounts = [0];
inAmounts.push(document.getElementById("amountIn").value);
outAmounts.push(document.getElementById("amountOut").value);
var sumIn = (inAmounts.reduce(function(a, b) {
return a + b[1];
}, 0));
var sumOut = (outAmounts.reduce(function(c, d) {
return c + d[1];
}, 0));
var result = initialBalance + sumIn - sumOut;
document.write(result);
};
displayCurrentBalance();
</script>
document.write(result); will overwrite your document before you even have a chance to enter the values. Make it display a value in another input box, or alert(result).
You should probably attach displayCurrentBalance to an onclick handler of some button, like <button onclick="displayCurrentBalance()">Calculate</button>.
document.getElementById("amountIn").value and similar calls will give you a string. You should use parseFloat or parseInt to convert it to an integer or a float.
You are likely calling the function before the elements are available in the page. Otherwise the script should be below the elements in the page.
You main problem is how you are using reduce. The values returned from the inputs are strings, so convert them to numbers before trying to add them (otherwise you will be concatenating strings, not adding numbers). You should probably validate the values too.
Also, reduce is called with the values of the members of the array, not the array itself (which is the 4th parameter provided to the callback, not the second), so:
var sumIn = (inAmounts.reduce(function(a, b) {
return +a + +b;
}, 0));
Modify the other call to reduce similarly. I don't think you need to provide an initial value since you initialise the array as [0]. Alternatively, keep the initial value in the call and initialise the array as [] (i.e. an empty array).
Rather than using document.write to display the result, better to write it as the value of a read–only input element so you can update it with subsequent calls as the user modifies the values in the other inputs.

How to reference an array in a function argument

I have a series of arrays that contain words I want to use as text in various HTML divs (there are about 35 of these, I included only a few for brevity).
var bodyplan = ['Anguilliform', 'Compressiform', 'Depressiform', 'Filiform', 'Fusiform', 'Globiform', 'Sagittiform', 'Taeniform'];
var mouthposition = ["Inferior", "Jawless", "Subterminal", "Superior", "Terminal"];
var barbels = ['1', '2', '4 or more'];
var caudalshape = ['Continuous', 'Emarginate', 'Forked', 'Lunate', 'Rounded', 'Truncate'];
I have a switch function that is supposed to change the text based on user selections:
switch(n){
case 1:
changelabels(bodyplan, 8);
break;
case 2:
changelabels(mouthposition, 5);
break;
case 3:
changelabels(barbels, 3);
break;
case 4:
changelabels(caudalshape, 6);
break;
case 5:
changelabels(dorsalspines, 8);
break;
default:
alert("handquestsel error")}};
Finally, I have the function which I would like to make the changes (except it doesn't):
function changelabels(opt1,opt2){
var i = opt2;
var im = opt2 - 1;
var c = 1;
var index = 0;
while (i>=c){
var oldlbl = document.getElementById("rb" + c + "lbl");
var newlbla = opt1.slice(im,i);
var newlblb = opt1.toString();
oldlbl.innerHTML = newlblb;
c = c + 1
index = index + 1
}};
I know the code for my function is just plain wrong at this point, but I have altered it so many times that I'm not sure what's going on anymore. At one point I did have the function able to change the text, but it did so incorrectly (it parsed the name of the array, not extracted a value from the array as I wished). Please help. I know I am overlooking some fundamental concepts here, but am not sure which ones. I've lost count of the hours I've spent trying to figure this out. It's seems like it should be so simple, yet in all my chaotic attempts to make it work, I have yet to stumble on an answer.
EDIT: I want my switch statement to call the function and pass to the function, the appropriate array from which to pull the labels from. The purpose of the app is to help a user learn to identify fish. When the user makes selections on the page, a series of pictures will be shown for various character states with an accompanying label describing the state. For example, when the user selects Mouth Position a series of divs will show the different mouth positions that fish have and have a label below the picture to tell the user what that certain character state is called. I can get the pictures to change just fine, but I am having a hell of a time with the labels.
Why not just something along the lines of:
document.getElementById("bodyplan_label").innerHTML = bodyplan[bodyplan_index];
You seem trying to put everything in really abstract data structures, I see no reason to. Just keep it simple.
Also bodyplan has only 8 elements, so bodyplan[8] will give you an out of bounds exception because arrays start at 0 as is common in all modern programming languages.
If I'm reading your requirement and code correctly, in your switch statement you are passing both a reference to the appropriate array and that array's expected length - you don't need the second parameter because all JavaScript arrays have a .length property.
You don't want to use .slice() to get the individual values out of the array, because that returns a new array copied out of the original - just use arrayVariable[index] to get the individual item at index.
So, putting that together try something like this (with your existing array definitions):
switch(n){
case 1:
changelabels(bodyplan);
break;
case 2:
changelabels(mouthposition);
// etc.
}
function changelabels(data) {
var i,
lbl;
for (i = 0; i < data.length; i++) {
lbl = document.getElementById("rb" + (i+1) + "lbl");
lbl.innerHTML = data[i];
}
}
Notice how much simpler that is than your code? I'm assuming here the elements you are updating have an id in the format "rb1lbl", "rb2lbl", etc, with numbering starting at 1: I'm getting those ids using (i+1) because JavaScript array indexes start at zero. Note also that you don't even need the lbl variable: you could just say document.getElementById("rb" + (i+1) + "lbl").innerHTML = data[i] - however I've left it in so that we have something to expand on below...
Within your function you seem to be changing the labels on a set of elements (radio button labels?), one per value in the array, but you stop when you run out of array items which means any leftover elements will still hold the values from the previous selection (e.g., if the previous selection was "bodyplan" with 8 options and you change to "mouthposition" with only 5 - you probably should hide the 3 leftover elements that would otherwise continue to display the last few "bodyplan" items. One way to do that is instead of setting your loop up based on the array length you could loop over the elements, and if the current element has an index beyond the end of the array hide it, something like this:
function changelabels(data) {
var i,
lbl,
elementCount = 20; // or whatever your element count is
for (i = 0; i < elementCount; i++) {
lbl = document.getElementById("rb" + (i+1) + "lbl");
if (i < data.length) {
lbl.innerHTML = data[i];
lbl.style.display = "";
} else {
lbl.innerHTML = "";
lbl.style.display = "none";
}
}
}
If these elements are labels for radio buttons (just a guess based on the ids) then you'd also want to hide or show the corresponding radio buttons, but I hope you can figure out how to add a couple of lines to the above to do that.
(As mentioned above, be careful about having element ids count up from 1 when the array indexes start at 0.)
If the above doesn't work please post (at least some of) the relevant HTML - obviously I've just had to guess at what it might be like.
SOLUTION: Changed the scope of the array variables to local by moving them into the function where they are used, instead of having them as global variables at the top of the page. I don't understand as I was following every rule of variable declaration. But for some unknown reason, global variables in javascript are abhorrent.
Solution Edit: Found an error in declaring my global variables. This may have been the source of my problem of why I could not access them. But it is a non-issue at this point since I corrected my code.
I don't understand what your trying to achieve exactly with your code. But to pass a variable (in this case an array) by reference you just have to add "&" before the variable.
function the_name(&$var_by_ref, $var_by_value) {
// Here if you modify $var_by_ref this will change the variable passed to the function.
}
More: http://php.net/manual/en/language.references.pass.php
Hope that helps.

Categories