Javascript - Conditionally selecting the condition of a while loop - javascript

I need to fill an array with randomly selected elements until the array reaches an appointed length. The length of that array must be equal to the smallest of two lengths. We'll call them length_1 and length_2. So if length_1 < length_2, then use length_1, otherwise, use length_2. Note that both lengths are constant so the statement length_1 < length_2 will always give the same Boolean value.
The method I came up with to deal with that situation is to create a while loop which, at each turn, adds a new randomly selected element to the array. It goes like this:
while (
length_1 < length_2
? array.length < length_1
: array.length < length_2
) {
// Add a new randomly selected element to the array
};
Is this a valid way to it? Is there a more concise way to go about it?

You could get the minimum in advance for a looping condition.
const
length = Math.min(length_1, length_2);
while (array.length < length) {
// ...
}

I try to avoid while loops. They are prone to get into an endless loop.
const length = Math.min(length_1, length_2);
for(let i = 0; i < length; i+=1) {
//...
}

Related

Apps Script For Loop stuck at 0 in iteration although it is running

I have an array 'vnData' containing 5, 6 rows from where I am trying to extract 3rd column values (based on a criteria) and insert to a new array. Here is my code
for (odr = 0; odr < vnData.length; odr++){
Logger.log(vnData);
tempOdr = vnData[odr][3];
Logger.log(odr);
Logger.log(tempOdr);
Logger.log(vnData[odr][3]);
for(k = 0; k < vnData.length; k++){
if(vnData[k][3] = tempOdr){
odrVal = odrVal + vnData[k][11];
}
}
if(odrVal > 0){
affOdrSet.push(tempOdr);
}
Logger.log(affOdrSet);
}
Logger gives right value of odr in Logger.log(odr); but in Logger.log(vnData[odr][3]); I am always getting a result where value of odr is 0.
So for each iteration I get value from first row. Please help what is wrong in it.
One more thing, if I log Logger.log(vnData[3][3]) in place of Logger.log(vnData[odr][3]) then for first iteration it gives me right value from row 4 but for all subsequent iterations even Logger.log(vnData[3][3]) gives value from first row which is really weird.
The problem is the expression of the first if statement. Instead of
vnData[k][3] = tempOdr
use
vnData[k][3] === tempOdr
The above because = is the assign operator but it's very likely that instead of assigning tempOdr to vnData[k][3] what you want to compare them.

Include duplicates in for and if loop of array as count number is too small

I'm new to javascript so any help would be greatly appreciated.
What I'm trying to do is cycle through every element in the array and count the number of times the value of an element matches a given condition (even if the value is duplicated).
function loaddata(xml) {
var count = 0;
var i;
var xmlDoc = xml.responseXML;
var z = xmlDoc.getElementsByTagName("group");
if (value1 <= value2) {
for (i = 0; i < (0 + z.length); i++) {
if (z[i].getElementsByTagName("name")[0].childNodes[0].nodeValue == "John") {
count++;
}
}
}
$('#count1').html(count);
};
The count value outputted is too small. I believe the reason for this that the for loop isn't iterating through all elements in the array. When I remove the second if loop and output the count for just the for loop this value is also too small. I believe that the for loop isn't searching through the duplicate elements of the array (i.e. it is ignoring them so that they aren't then fed into the second if loop). Is it possible to specify that the for loop include duplicates?
Do a console.log(z[i].getElementsByTagName("name")) and open your browser's console, and see if that array has data in it.
Then console.log(z[i].getElementsByTagName("name")[0].childNodes) and make sure you have nodes in it.
Also, do you have many <group></group> tags? Because that's what you are selecting with var z = xmlDoc.getElementsByTagName("group");
I hope that helps,

Get last 4 characters of every element of array in JavaScript

I would be surprised if this hasn't been asked in the past. I was unable to find something that works. I have an array of strings and I would like to create a new array with only the last 4 characters of each of the elements. The code is below. What do I need to change to make it work?
for(i=0; i<userScanDataObjects.length;i++){
// if statement used to select every alternative element from the array as th rows are duplicated
if (i%2 !==0){
deviceID_raw.push(userScanDataObjects[i].deviceID.value);
deviceID.push(deviceID_raw[i].substring(5,8));
}
['11114444', '22224444'].map(function(string) { return string.substring(string.length - 4, string.length) })
You can use Array.map depending on your targeted browser support/polyfills. And you can do the following:
for( var i = 0; i < array.length; ++ i ) {
array[i] = array[i].substr(-4);
}

javascript : after calling the splice() control comes out from the loop

I have an array rosters and i want to alter this array according to some conditions. Here what I'm trying to do.
somefunction(callback) {
for (var i in this.rosters) {
var roster = this.rosters[i];
if (roster.age > 7200) {
this.rosters.splice(i, 1);
} else {
this.rosters[i].age = this.EMarshal.tu.getAgeOfTime(
this.EMarshal.tu.getMyTime(
this.EMarshal.tu.getMyDate(roster.date), roster.shifttime
)
);
console.log(this.rosters[i].age);
}
}
callback();
}
When the the if condition is true and splice is been called, control comes out of from loop and call callback(). But i want to run the loop for each values in the array.
plz carefully notice that there are rosters and roster 2 different variables.
Any idea why its happening and the solution will be usefull.
Thanks
It's just because you are trying to alter the array on which you are iterating.
So, just ad some logic to store the indexes as you have said you have tried.
Here is one suggestion
before getting into loop var index = [];
then your if condition
if (roster.age > 7200) {
index.push(i);
}
and then after the loop, remove those indexes from rosters
for (var j = index.length - 1; j > -1; j-- ) {
console.log(j);
this.rosters.splice(index[j], 1);
}
Remember to iterate the index from last index otherwise you will remove the 1st index and the trying to remove the last index from the rosters, but now you have removed the element from the array so the length is been changed.

javascript array for loop i+1 returning undefined

array ref.length = 7 (0 - 6), and I want to try to match ref[0]['x'] to ref[1]['x'] I am doing this:
for(var i=0;i<ref.length;i++){
if( ref[i]['x'] != ref[i+1]['x'] && ref[i+1]['x'].length > 0 )
//do something
}
The for loop is iterating all the way to array number 6 then element 6+1 is blank so I get an error on the if statement line saying ref[i+1] is undefined....
is there a better way to do this?
Better:
for (var i=ref.length-2;i>=0;i--)
Javascript will evaluate the condition on each iteration, so it's generally preferable go backwards instead. With this construct "ref.length" is only evaluated once. Another alternative I like which will perform the same:
var i=ref.length-1;
while (i--) {
}
(Normally you'd be i=ref.length-1 in the first example, and i=ref.length in the second, but you're trying to stay one less than the array length).
for (var i=0; i<ref.length-1; i++) { // Note the "-1".
This way when you use the index i+1 you're still in bounds.
for (var i = 0; i < ref.length - 1; i++)
What about:
for(var i=0;i<ref.length-1;i++){
If you just use ref.length-1 won't that solve your problem? I might not fully understand what you're asking.
Here's a simple solution.
Just count the counter again.
if( ref[i]['x'] != ref[++i]['x'] && ref[++i]['x'].length > 0 )

Categories

Resources