Appending text through loop iteration - javascript

Not sure why I'm having a hard time with this. I think it's getting late in the day probably but --
I'm pulling database values into an array. The current array is: [1,3]. I'm then stepping through the array and appending a prefix to the values (in this case: "&Plantkey=") in order for the final string to have the format of:
&Plantkey=1&Plantkey=3
Here's my code so far:
if (array[a].ParameterName == "Plantkey") {
var plantKey = array[a].ParameterValue;
var plantTemp = [];
plantTemp = plantKey.split(",");
for (var p = 0; p < plantTemp.length; p++) {
var plantKeyString = ("&Plantkey=" + plantTemp[p]);
}
}
I'm only getting the last array value (&Plantkey=3). With javascript, it doesn't like me instantiating the "var plantKeyString" and adding the "+=" operator. If I instantiate the array above the for loop, like so:
var plantKeyString;
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
Then I end up with a longer string, including the array values I want but it also pulls in the "undefined" value that it finds at the beginning so it looks like this:
undefined&Plantkey=1&Plantkey=3
I could easily look for the "undefined" and remove it but I'm sure the problem is with the loop iteration, not the data, obviously.
Any help would be greatly appreciated! Thanks!

The reason you are getting only the last value in the first case is because you are redeclaring a new plantKeyString for each loop hence only the last declaration stays.
with the second solution just do the following and it should work:
var plantKeyString="";
for (var p = 0; p < plantTemp.length; p++) {
plantKeyString += ("&Plantkey=" + plantTemp[p]);
}
The reason you were getting the undefined at the beginning of your final result was because 'plantKeyString' is 'undefined' as you have not given it a value. In javascript all variables are undefined till you give them a value. So in the solution that I have provided you are just instantiating it with an empty string.

You can do it in a succinctly way simply using array join() method and add &Plantkey= at first as follows:
var plantKeyString = '&Plantkey=' + array.join('&Plantkey=');
For an [1,3] array this code produces what you expect: &Plantkey=1&Plantkey=3, try with this code sample:
var array = [1,3];
var plantKeyString = '&PlantKey=' + array.join('&PlantKey=');
alert(plantKeyString);
See join() description here

Related

Two Dimensional Array - arr[i][0] Gives Wrong Result - JavaScript ASP.NET C#

I have an Array of Arrays populated from C# Model:
var AllObjectsArray = [];
#foreach(var Cobject in Model.ObjectList)
{
#:AllObjectsArray.push(new Array("#Cobject.Name", "#Cobject.Value", "#Cobject.Keyword"));
}
var SelectedObjects = [];
uniqueobj.forEach(function (element) {
SelectedObjects.push(new Array(AllObjectsArray.filter(elem => elem[0] === element))); //makes array of selected objects with their values(name,value,keyword)
});
I am trying to get second parameter of each and every inner Array and add it to new array containing those elements like this:
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][0]) //problem here i think
};
Unfortunately, on:
alert(ValuesArray + " : " + SelectedObjects);
I get nothing for ValuesArray. The other data for SelectedObjects loads properly with all three parameters correctly returned for each and every inner Array,so it is not empty. I must be iterating wrongly.
EDIT:
SOme more info as I am not getting understood what I need.
Lets say SelectedObjects[] contains two records like this:
{ name1, number1, keyword1}
{ name2, number2, keyword2}
Now, what I need is to populate ValuesArray with nane1 and name2.
That is why I was guessing I should iterate over SelectedObjects and get SelectedObject[i][0] where in my guessing i stands for inner array index and 1 stands for number part of that inner array. Please correct me and put me in the right direction as I am guesing from C# way of coding how to wrap my head around js.
However SelectedObject[i][0] gives me all SelectedObject with all three properties(name, value and keyword) and I should get only name's part of the inner Array.
What is happening here?
Hope I explained myself better this time.
EDIT:
I think I know why it happens, since SelectedObjects[i][0] returns whole inner Array and SelectedObjects[i][1] gives null, it must mean that SelectedObjects is not Array of Arrays but Array of strings concatenated with commas.
Is there a way to workaround this? SHould I create array of arrays ddifferently or maybe split inner object on commas and iteratee through returned strings?
First things first, SelectedObjects[i][1] should rather be SelectedObjects[i][0].
But as far as I understand you want something like
var ValuesArray = [];
for (let i = 0; i < SelectedObjects.length; i++) {
for(let j = 0; j <SelectedObjects[i].length; j++) {
ValuesArray.push(SelectedObjects[i][j]);
}
};
In this snippet
var ValuesArray = [];
for (i = 0; i < SelectedObjects.length; i++) {
ValuesArray.push(SelectedObjects[i][1]) //problem here i think
};
You're pointing directly at the second item in SelectedObjects[i]
Maybe you want the first index, 0

How to return a line from an array by searching for a specific value in said line

good evening, I am trying to use a single value to search an array, and return the full line the said value is in.
The Array is set up like this in string form:
Xanax,Brand,Anxiety,Code
However, now I'm stuck with calling back only the Medication, and not the full line the Medication is in, sadly. I would like to be able to grab each variable in a line, and make them their own independent variables outside of the array so I can use them for something else.
this.importDataObject("MEDDIAGNOSISICD-10.txt", "C:/Users/dell/Documents/tab
excel/MEDDIAGNOSISICD-10.txt");
var oFile = this.getDataObjectContents("MEDDIAGNOSISICD-10.txt");
var cFile = util.stringFromStream(oFile, "utf-8");
var fileArray = cFile.split('\t');
var Med = this.getField("Medications 1");
var Index = fileArray.indexOf(Med.value);
var Call = fileArray[Index];
console.println(Call);
Any help would be wonderful!
It's because you are running the indexOf method on the whole array, you need to run it on the each value instead. Try a for loop before you check IndexOf method.
Like this:
var i, Index;
for (i = 0; i < fileArray.length; i++) {
Index = fileArray[i].indexOf(Med.value);
if(Index > -1) console.log('Your search is found in ' + fileArray[i] );
}
Note that, in here the variable Index will be 0 or larger if that search is successful. And will be of value -1 if no match is found.

Google scripts. TypeError: Cannot call method "replace" of undefined

First post please go easy on me.
I have an array that looks something like this [BTC-LTC, BTC-DOGE, BTC-VTC] I am trying to change all the "-" with "_". But am having trouble with using the .replace() method. Here is my code.
var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
var str = JSON.stringify(array[i]);
var res = str.replace("-","_");
fixedArray.push(res);
};
I tried without using the JSON.stringify but that didn't work either. I have also tried to first create var str = String(); this also did not work. Is it possible that the method .replace() is not available in google scripts?
In your example var array = [BTC-LTC, BTC-DOGE, BTC-VTC];
should be
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
However I gather from the comments that this is just a typo in your initial example.
var str = JSON.stringify(array[i]); is redundant. You can just do var str = array[i]; Since the value in the array is already a string, there's no need to turn it into one again - the "stringify" method expects to be given an object or array to work on.
However the main problem is that your for loop goes on one too many iterations. Arrays are zero-based, so you need to stop looping when the index is 1 less than the length of the array, not equal to it. e.g. if array.length is 10 then there are 10 indices, but they start at 0, so the indices are 0,1,2,3,4,5,6,7,8,9. If your loop goes on to equal to array.length, then on the last loop array[10] will be out of bounds, and it's only this last iteration which is giving you the undefined error.
var array = ["BTC-LTC", "BTC-DOGE", "BTC-VTC"];
var fixedArray = [];
for (var i = 0; i < array.length; i++) {
var str = array[i];
var res = str.replace("-","_");
fixedArray.push(res);
}
If I understood correctly, you're trying to edit strings, not variables, so you need quotes in your array, and a g in your replace in case you have multiple things to replace :
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];
var fixedArray = [];
for(var i=0; i <= array.length; i++){
fixedArray.push(array[i].replace(/-/g, '_'));
};
code is working fine if we change as below:
var array = ['BTC-LTC', 'BTC-DOGE', 'BTC-VTC'];

Get length of longest String in Array

i need to find out the longest string of an array. First of all i push different "text" elements into my array, since the stringe and amount of those "text" elements can differ from case to case. (they are lables of an chart and thus are generated based on the charts sections.
my code right now looks like this:
var textLengthArray = [];
domContainer.find(" g > .brm-y-direction > .tick > text").each(function () {
textLengthArray.push($(this));
});
var lgth = 0;
var longestString;
for (var i = 0; i < textLengthArray.length; i++) {
if (textLengthArray[i].length > lgth) {
var lgth = textLengthArray[i].length;
longestString = textLengthArray[i];
}
}
It already pushes all text elements into my array. But when i use
alert(longestString.length)
i allway get "1" as a result. I am pretty shure i have to add .text anywhere before .length, since the code does not check die textlength of the textelements.
Since i am quite new to javascript i would highly appreciate some help.
Thanks in advance!
textLengthArray.push($(this)); should be textLengthArray.push($(this).text()); otherwise your array consists of jQuery objects. And indeed jQuerySet has length property. And in your case the set consists of 1 element.
You are re-declaring lgth in each iteration of the array which is re-assigning the value.
Replace var lgth = textLengthArray[i].length with lgth = textLengthArray[i].length and you should be good.
I don't know about the rest of your code, looks fine. But you're pushing a jQuery object$(this), not a string. Line three should read textLengthArray.push(this);.
Apparently one of the strings your pushing is a valid jQuery selector that finds an element :-)
No need to create a separate array. Just iterate objects and update as you go:
longest = "";
$('div').each(function() {
var t = $(this).text();
if(t.length > longest.length)
longest = t;
});
alert(longest)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>hello</div>
<div>wonderful</div>
<div>world</div>
To get the longest string from any array, try reduce:
a = ['hello', 'wonderful', 'world']
longest = a.reduce(function(prev, e) {
return prev.length >= e.length ? prev : e;
});
alert(longest)
Sort the array by length and get the first element. Hope it works for you
stackoverflow.com/questions/10630766/sort-an-array-based-on-the-length-of-each-element

Cannot access second field in a 2 dimension array in javascript

I have a 2 dimension array defined as
var thischart = [[],[]];
and the array contains the following data created programatically:
1,0,2,0,3,0,4,0,5,0,6,0,7,0,8,0,9,0,10,0,11,0,12,0,13,24,14,0,15,0,16,0,17,0,18,0,19,0,20,0,21,0,22,0,23,0,24,0
I cannot get the single value of the second field in the particular array cell. For example, if I use the following command to get the value:
alert("thischart[i,1]=" + thischart[0, 1]);
I get the following answer:
thischart[i,1]=2,0
I tried using the second dimension to access the data as
thischart[0][1]);
but it gives me an error message:
I just want to get the second single value in the array such as for array cell 13 I want the value 24 from above. Does anyone have an answer on how to access this array?
I populated the array as follows and then updated it thru program logic:
$hours = [];
for($i = 0; $i< 24; $i++){
$hours[$i] = [];
$hours[$i][0] = ($i + 1);
$hours[$i][1] = "0";
}
And the answer to this question is below:
for(var i in thischart){
var tc = thischart[i];
myvalue = tc[1]); // this is the value I want
}
Thanks to everyone who responded.
For all of them like this:
for(var i in thischart){
var tc = thischart[i];
for(var n in tc){
// n is internal index
// tc[n] is internal value
}
}
For a single value from the first internal Array, the second value:
thischart[0][1];
Why don't you use the console to see what's the return of
thischart[0];
Because it should contain an array. If it does, then
thischart[0][1];
is perfectly valid syntax. And if it doesn't, then
thischart[0,1]
means nothing whatsoever.
Do something like this:
var items = [[1,2],[3,4],[5,6]];
alert(items[0][0]); // 1
do you mean something like this:...
http://jsfiddle.net/DSrcz/1/
var arr = [1,0,0,0,0,0,0,0,0,0,0,0,0,24,0,0,0,0];
arr[33]=1000;
alert(arr[13]);
alert(arr[33]);

Categories