Get length of longest String in Array - javascript

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

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.

Passing array elements to foreach divs

I'm trying to pass string elements from an array myArr while selecting the div it should go into with a forEach loop, so that each of the four div elements below has a corresponding string element from the array.
I'm having some trouble with it, because I'm selecting the divs with a querySelectorAll method. Help would be appreciated. This code below is just a sample of what I'm working on, so it can't be altered too much.
HTML
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
<div class="number">old number</div>
JS
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
numberDivs.forEach(function(el) {
el.innerHTML = "new number";
for (var i = 0; i < myArr.length; ++i) {
el.innerHTML = myArr[i];
}
});
Right now, it's (el) only passing through the last element in the array to all divs, instead of the corresponding one.
I think is this what you want:
numberDivs.forEach(function(el, i) {
el.innerHTML = myArr[i];
});
This assumes they are of equal length, and won't overwrite each element's HTML like your code is currently doing.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
for (var i = 0; i < myArr.length; i++) {
numberDivs[i].innerHTML = myArr[i];
}
You're issue was you had a for loop going across all the elements, then another for loop going across your array. The inner for loop, the one for you're array, would always end at the last element, therefore each object - the divs - ended at the final element of that array.
http://jsfiddle.net/a8zrkejo/
Quick fix, if you're certain the total count of the array is same as the number of divs
then loop the array only and use the index of each element to access the div.
var numberDivs = document.querySelectorAll(".number");
var myArr = ['number1','number2', 'number3', 'number4'];
myArr.forEach(function(value, Index) {
numberDivs[Index].innerHTML = value
});

Appending text through loop iteration

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

How to split a URL string with parameters into an array using JavaScript

I'm trying to break up a string like this one:
fname=bill&mname=&lname=jones&addr1=This%20House&...
I want to end up with an array indexed like this
myarray[0][0] = fname
myarray[0][1] = bill
myarray[1][0] = mname
myarray[1][1] =
myarray[2][0] = lname
myarray[2][1] = jones
myarray[3][0] = addr
myarray[3][1] = This House
The url is quite a bit longer than the example. This is what I've tried:
var
fArray = [],
nv = [],
myarray = [];
fArray = fields.split('&');
// split it into fArray[i]['name']="value"
for (i=0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push(nv[0],nv[1]);
nv.length = 0;
}
The final product is intended to be in 'myarray' and it is, except that I'm getting a one dimensional array instead of a 2 dimensional one.
The next process is intended to search for (for example) 'lname' and returning the index of it, so that if it returned '3' I can then access the actual last name with myarray[3][1].
Does this make sense or am I over complicating things?
Your line myarray.push(nv[0],nv[1]); pushes two elements to the array myarray, not a single cell with two elements as you expect (ref: array.push). What you want is myarray.push( [nv[0],nv[1]] ) (note the brackets), or myarray.push(nv.slice(0, 2)) (ref: array.slice).
To simplify your code, may I suggest using Array.map:
var q = "foo=bar&baz=quux&lorem=ipsum";
// PS. If you're parsing from a-tag nodes, they have a property
// node.search which contains the query string, but note that
// it has a leading ? so you want node.search.substr(1)
var vars = q.split("&").map(function (kv) {
return kv.split("=", 2);
});
For searching, I would suggest using array.filter:
var srchkey = "foo";
var matches = vars.filter(function (v) { return v[0] === srchkey; });
NB. array.filter will always return an array. If you always want just a single value, you could use array.some or a bespoke searching algorithm.
for (var i = 0; i < fArray.length; i++) {
nv = fArray[i].split('=');
myarray.push([nv[0],nv[1]]);
}
nv.length = 0; is not required, since you're setting nv in each iteration of the for loop.
Also, use var i in the for-loop, otherwise, you're using / assigning a global variable i, that's asking for interference.

Categories