If value == 1 then get the next value in the array - javascript

var countries = [1,"DK",2,"USA",3,"Sweden",];
var languages = [2,"EN",3,"Swedish",1,"Danish"];
var population = [2,"300000000",1,"6000000",3,"8000000"];
In javascript, is there a way to look for a value in an array, for example if the value is 1, then take the next value in the array. Here it would be DK, Danish and 6000000.
I have this but think it should be way to do it more simple
for(var i = 1 ; i < countries.length; i = i+2){
var countryName = countries[i];
var countryId = countries[i-1];
for(var j = 0; j < languages.length; j = j+2){
if(languages[j] == countryId){
var positionSpokenLanguage = j + 1;
var spokenLanguage = languages[positionSpokenLanguage];
}
if(population[j] == countryId){
var positionPopulation = j + 1;
var totalPopulation = population[positionPopulation];
}
}
var message = "In "+countryName+" people speak "+spokenLanguage+
" and there are "+totalPopulation+" inhabitatns";
console.log(message);
}

As you are actually looking for a value in every other item in the array, there is no built in method for that.
If you know that the value is in the array, you can just loop until you find it:
var index = 0;
while (countries[index] != 1) index += 2;
var value = countries[index + 1];
Your data has an unintuitive format, which makes it a bit awkward to work with. If possible you should use a data format where you don't mix keys with values, for example an object:
var countries = { 1: "DK", 2: "USA", 3: "Sweden" };
Then you can just get the value using the key:
var value = countries[1];

Related

Finding two elements within an array with IF statement using Apps Script

I am very new to programming and I am trying to locate two consecutive values within a 1-d array in google sheets and the answers need to be highlighted in bold in the google sheet. The first value should be greater than 5 (located for example in cell D10) and the next value should be less than 4.99 (and located in E10). I have tried two methods but can't seem to get the Code to work - I don't know if I am over-complicating the problem or not. The first method was to make the row into 2 separate arrays of elements so that if element J is greater than 5, and element k (which looks at the element next to J) is less than 4.99.
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var ui2 = SpreadsheetApp.getUi();
var data1 = ss.getRange(10,2,1,20).getValues()[0]; //Variable 1 - to find the ON value B10:U10
var data2 = ss.getRange(10,3,1,20).getValues()[0]; //to find the OFF value;
var onA = 5.00;
var on = data1 > onA;
var offA = 4.99;
var off = data2 < offA;
for(var i = 0; i < 20; i++){
for(var j = 0; j < 20; j++){
if(data1[i] < 5.00 && data2[j] < 4.99){
ss.getRange(10,2,1,20).setValue(data1[i]).setFontSize(12).setFontWeight("bold");
ss.getRange(10,3,1,20).setValue(data2[j]).setFontSize(12).setFontWeight("bold");
break;
}
else {
ui2.alert("the values are not found");
break;
}}}}
My other method was not search the cells as a single array - this works but once I add a message to a else statement to state the values are not found it would repeat this alert for the same number of times as the loop.
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var ui2 = SpreadsheetApp.getUi();
for(var j = 2; j < 22; j++){ // j is column number
for(var k = j+1; k < 23; k++){
var result = ss.getRange(10,j).getValue();
var result2 = ss.getRange(10,k).getValue();
var resulta = result > 5.00;
var resultb = result2 < 4.99;
if (resulta == true && resultb == true) {
ss.getRange(10,j).setValue(result).setFontSize(12).setFontWeight("bold");
ss.getRange(10,k).setValue(result2).setFontSize(12).setFontWeight("bold");
break;
} else {
break;
ui2.alert('Values not found');
}}}}
Any help would be amazing and very greatly appreciated!
Try this:
function findconsecutives() {
const ss=SpreadsheetApp.getActive();
const sh=ss.getSheetByName('Sheet1')
const rg=sh.getRange(10,2,1,20);
const vs=rg.getValues()[0];
for(let i=0;i<vs.length-1;i++) {
if(vs[i]<5 && vs[i+1]<4.99) {
sh.getRange(10,i+2,1,2).setFontSize(12).setFontWeight('bold');
break;
}
}
ss.toast('not found');
}
I just changed the fontsize and fontweight to the cells that meet the requirements if you want to change feel free. I don't want to.

Problems accesing external database inside For iterator

I have an array called countriesData that stores names for various countries, like this:
[Germany,France,Canada,Austria,Switzerland,Spain]
I'm trying to iterate over each element in that array, the idea is use each country in a query search over an external API, and then save the length of items in that external API. To put it simple, Im going through each country and counting how many items from that country are stored in an external database.
I have no problem accessing the database outside of the loop, however, I am unable to access it while inside the for iterator.This is my code:
for (var iter = 0; iter < countriesData.length; iter++) {
var obj = [];
var country = countriesData[iter]
var items;
var itemsCountry = 0;
$http.get("https://api.discogs.com/database/search?q={?country==" + country + " }&token=zwxZExVZTenjPTKumVeTDVRuniqhQLAxymdzSxUQ").then(function(response) {
items = response.data.pagination.items;
})
var str = "";
obj.push(countriesData[iter]);
obj.push(items);
for (var J = 0; J < myStats.data.length; J++) {
if (myStats.data[J].country == countriesData[iter]) {
itemsCountry++;
str += myStats.data[J].title + ", ";
}
}
obj.push(itemsCountry);
var str2 = str.substring(0, str.length - 2);
obj.push(str2);
newData.push(obj);
console.log("new obj : " + obj)
}
Basically, I need the var items to be updated acording to the length of the response data from http.get
This is an example of what I get once I console.log the obj:
France,,2,Thriller, D'eux
As you can see, the second element in the array is empty when it should have been an integer representing how many France related items where found in the database...
What is it that Im doing wrong? I get that the database is big and there might not be enough time for it to load. Any idead?
Thanks in advance :)
The problem is that your data call is asynchronous and hasn't completed before you try to push the data to the array.
function getCountryData(country) {
var obj = [];
var items;
var itemsCountry = 0;
$http.get("https://api.discogs.com/database/search?q={?country==" + country + " }&token=zwxZExVZTenjPTKumVeTDVRuniqhQLAxymdzSxUQ").then(function(response) {
items = response.data.pagination.items;
var str = "";
obj.push(country);
obj.push(items);
for (var J = 0; J < myStats.data.length; J++) {
if (myStats.data[J].country == countriesData[iter]) {
itemsCountry++;
str += myStats.data[J].title + ", ";
}
}
obj.push(itemsCountry);
var str2 = str.substring(0, str.length - 2);
obj.push(str2);
newData.push(obj);
console.log("new obj : " + obj)
})
}
for (var iter = 0; iter < countriesData.length; iter++) {
var country = countriesData[iter];
getCountryData(country);
}

Create a list of objects in acrobat using javascript not same as regular javascript?

I am trying to create a list of objects using javascript for an acrobat form. But the usual javascript code used does not work.
This is the code that I am using:
function updatePage1(totalRows)
{
var B = [];
var totalRows = 25;
for(var i = 1; i <= 1; ++i)
{
app.alert(i);
app.alert(this.getField("CostHead"+i.toString()).value);
var costhead = this.getField("CostHead"+i.toString()).value;
B.push({
1 : { cost : 0.00, val: costhead }
});
}
var valu = B[1].cost;
app.alert(valu);
}
Can anyone help ?
There are two ways to fix this... If you MUST use the row number as the key and you have an array of objects, you're going to need to change the row number to a string.
function updatePage1(totalRows)
{
var B = [];
var totalRows = 25;
for(var i = 1; i <= 1; ++i)
{
app.alert(i);
app.alert(this.getField("CostHead"+i.toString()).value);
var costhead = this.getField("CostHead"+i.toString()).value;
B.push({
"1" : { cost : 0.00, val: costhead }
});
}
var valu = B["1"].cost;
app.alert(valu);
}
But a better fix is to ditch the row number altogether and just rely on the array order to get the object you need. Start your increment at 0.
function updatePage1(totalRows)
{
var B = [];
var totalRows = 25;
for(var i = 0; i < totalRows; ++i)
{
app.alert(i);
app.alert(this.getField("CostHead")+(i+1).toString()).value);
var costhead = this.getField("CostHead"+(i+1).toString()).value;
B.push({ cost : 0.00, val: costhead });
var valu = B[i].cost;
app.alert(valu);
}
}

Using counter in variable name

This is what I have currently but I cant get v(i) to behave the same as v1. What am I doing wrong?
I've also tried the piece below which also did not work.
var x = "v" + i;
alert(x);
My main problem is the following:
var v1 = document.getElementById("thing1").innerHTML; // = 100
var v2 = document.getElementById("thing2").innerHTML; // = 150
var v3 = document.getElementById("thing3").innerHTML; // = 200
for (i = 0; i < 4; i++) {
if ( v(i) != ""){
alert(v(i));
}
}
Thanks in advance:)
What you are trying to do is not easily accomplished. You would have to assign the variable to the window object and then print it from there.
A much better solution is to use your own object or array to handle this:
var v1 = document.getElementById("thing1").innerHTML; // = 100
var v2 = document.getElementById("thing2").innerHTML; // = 150
var v3 = document.getElementById("thing3").innerHTML; // = 200
var array = [v1,v2,v3];
for (i = 0; i < 4; i++) {
if ( array[i] != ""){
alert(array[i]);
}
}
All global variables are properties of window object you could use window['v'+ i] or this['v'+ i] to create them.
But this is very bad pattern consider using object instead.
What you are trying to do is get an interpolated variable name, which is not possible in javascript the way you do it.
You can do this using this['v'+i] or window['v'+i] which are both bad ideas in the global scope.
v(i) actually means: run function v(...) with parameter i
If i would write your example code in easy to understand javascript, i would come up with this:
for(var i = 1; i <= 4; i++)
{
var html = document.getElementById('thing'+i).innerHTML;
alert(html);
}
If you want your values in an array, in a way that you don't write the same code 6 times:
var ids = ['thing1','thing2','thing3','thing4'];
// es5
var values = [];
for(var i = 0; i < ids.length; i++)
{
var html = document.getElementById( ids[i] ).innerHTML;
values.push( html );
}
// values now contains all the values of the elements
// OR es 6
var values = ids.map(function(id) { return document.getElementById(id).innerHTML; });
// or
var values = ids.map(id => document.getElementById(id).innerHTML);
You could use an array without using single variables and loop it.
var array = [
'100', // document.getElementById("thing1").innerHTML,
'150', // document.getElementById("thing2").innerHTML,
'200' // document.getElementById("thing3").innerHTML
],
i;
for (i = 0; i < array.length; i++) {
if (array[i] !== "") {
console.log(array[i]);
}
}
If you need some keys, you could use an object.
var object = {
v1: '150', // document.getElementById("thing1").innerHTML,
v2: '200', // document.getElementById("thing2").innerHTML,
v3: '250', // document.getElementById("thing3").innerHTML
},
i;
for (i = 1; i <= 3; i++) {
if (object['v' + i] !== "") {
console.log(object['v' + i]);
}
}

trouble filling bidimensional Array with objects in JavaScript

I've got this array in a "global" position (out of every function in my doc).
var arrayBidimensional;
Then, i'm trying to filling it like this:
var objetoLetra = new objectLetter("","","","","");
arrayBidimensional=new Array(tamano);
for (i=0; i <tamano; i++)
arrayBidimensional[i]=new Array(tamano);
var random = Math.floor((Math.random()*26)+0);
for (var i = tamano - 1; i >= 0; i--)
{
for (var j = tamano - 1; j >= 0; j--)
{
random = Math.floor((Math.random()*26)+0);
objetoLetra.letra = letras[random];
objetoLetra.letraposx = j;
objetoLetra.letraposy = i;
objetoLetra.formapalabra = "no";
objetoLetra.iden = j+""+i;
arrayBidimensional[i][j] = objetoLetra;
}
}
so when i tried to reach to this array in some position like array[X][X]
all i've got is the very first position. Example: if the first position (That is 0,0) is "A", then, the entire array got "A" on every single position, even if it is [(max position), (max position)].
How do i see that?, well, i'm building a Table with td-s like this:
'<td width="30">'+arrayBidimensional[i][j].letra+'</td>'
Then, the entire table is just a lot of "A" every single cell... So... What i am doing wrong?
Please and thank you!
You need to create a new objectLetter for each location in the array:
arrayBidimensional = new Array(tamano);
for (i=0; i < tamano; i++) {
arrayBidimensional[i] = new Array(tamano);
}
for (var i = tamano - 1; i >= 0; i--)
{
for (var j = tamano - 1; j >= 0; j--)
{
var objetoLetra = new objectLetter("","","","","");
var random = Math.floor((Math.random()*26)+0);
objetoLetra.letra = letras[random];
objetoLetra.letraposx = j;
objetoLetra.letraposy = i;
objetoLetra.formapalabra = "no";
objetoLetra.iden = j+""+i;
arrayBidimensional[i][j] = objetoLetra;
}
}
Here's what a Multidimensional Array should look like in JavaScript:
var multi = [['String', 0, 'something else'],['another String', 42, 'whatever']];
or
var multi = new Array(new Array('String', 0, 'something else'), new Array('another String', 42, 'whatever'));
console.log(multi[1][2]); // 'whatever'
console.log(multi[0][1]); // 0

Categories