how do I find an object's index number in an array - arrays

I've got this code that is looking for the closest number to 0 in my array :
var tideArray = new Array();
tideArray.push({tide:"haute", difference: "-14"});
tideArray.push({tide:"haute", difference: "3"});
tideArray.push({tide:"basse", difference: "-4"});
tideArray.push({tide:"basse", difference: "8"});
if (tideArray.length > 0)
{
var minItem: Object = tideArray[0];
for (var index:int = 1; index < tideArray.length; index++)
{
if (Math.abs(tideArray[index].difference) < Math.abs(minItem.difference))
{
minItem = tideArray[index];
}
}
}
trace(minItem.difference) // OUTPUT is 3 in this case
s there a way to find the index of minItem.difference in my tideArray ? (so, the result here should be index = 1 )
I've tried tideArray.indexOf(minItem.difference) but the output is -1, so the index wasn't found...
I'm looking for the index number and not the value of "difference" or "tide".

Try using map, e.g.:
tideArray.map(function (cv) { return cv.difference }).indexOf("-14")

A really simple approach would be to record the index using your existing loop:
if (tideArray.length > 0)
{
var mindex: int = NaN;
var minItem: Object = tideArray[0];
for (var index:int = 0; index < tideArray.length; index++)
{
if (Math.abs(tideArray[index].difference) < Math.abs(minItem.difference))
{
minItem = tideArray[index];
mindex = index;
}
}
trace("Min item index: " + mindex);
}

Related

How to set in Google Sheets an x time-efficient in all rows that contain a value according to getValues for example?

In the cells of the D column there is the following formula to get the actual row number (non-hidden rows): =if(subtotal(103,A?),row(),"").
function x() {
var s = SpreadsheetApp.getActive().getActiveSheet();
var values = s.getRange('D2:D').getValues();
var index = 0;
var value = values[index];
var condition = /\S/.test(value); // printable char
var ranges = [];
for (values; ?; index++) { // until the last index
if (condition) {
ranges.push('C'+value);
}
}
s.getRangeList(ranges).setValue('x');
}
A for-loop should have 3 optional expressions: intialization(var index = 0), condition (index < values.length)and final-expression(index++).
The variables that change(value and condition) in the loop should be inside the for-loop
function x() {
var s = SpreadsheetApp.getActive().getActiveSheet();
var values = s.getRange('D2:D').getValues();
var ranges = [];
for (var index = 0; index < values.length; index++) { // until the last index
var value = values[index];
var condition = /\S/.test(value); // printable char
if (condition) {
ranges.push('C'+value);
}
}
s.getRangeList(ranges).setValue('x');
}

Dynamic if statement in Google script

I have the function below which sets values in an array to "" if each value in the row is identical and then removes the blank values from the array
If I have
arr = [[[a],[a]],[[a],[b]],[[a],[c]],[[b],[a]],[[b],[b]],[[b],[c]],[[c],[a]],[[c],[b]],[[c],[c]]]
I end up with
[[[[a],[b]],[[a],[c]],[[b],[a]],[[b],[c]],[[c],[a]],[[c],[b]]]]
But what if my array has n dimensions instead of just two
I can't figure out how to write this part dynamically
for (var i = 0; i < values.length; i++) {
if (values[i][0] == values[i][1]) {
values[i][0] = '';
values[i][1] = '';
}
}
So that the if statement was testing
values[i][0] == values[i][1]... ==values[i][n]
Thanks
My Function
function removeEmptyRng(shtName, rng, outputRng) {
var sht = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(shtName);
var lr = sht.getLastRow();
var range = sht.getRange(rng + lr);
var values = range.getValues();
for (var i = 0; i < values.length; i++) {
if (values[i][0] == values[i][1]) {
values[i][0] = '';
values[i][1] = '';
}
}
//Remove Empty values
values = values.filter(function(a) {return a.filter(Boolean).length > 0;});
if (outputRng == true)
{sht.getRange(1,2,values.length,values[0].length).setValues(values)};
return values
}
You could immediately filter for the inequality in the whole row... Basically saying "keep a row if one of its values is unequal to the first of the row" => not all are equal.
values = values.filter(
function(row) {
return row.some(
function(val) {
return val != row[0]});
});

TypeError: Impossible to find getCell function in the Sheet object

I'm trying to get some data from a Google Sheet to insert in two arrays with a for loop but I think I'm using the wrong methods.
This is the code:
function regValori() {
var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
var CValue = new Array();
var CName = new Array();
CValue.lenght = datAgg.getRange("B1").getValue();
CName.lenght = CValue.lenght;
for (var i = 0; i <= CValue.lenght; i++)
{
CValue[i] = datAgg.getCell(i, 16).getValue();
CName[i] = datAgg.getCell(i+2, 1).getValue();
}
var riga = f5.getRange("B2").getValue();
for (x = 3; x <= numCrypto; x++);
for (i=0;i<numCrypto;i++);
{
f5.getRange(riga, x).setValue(valCrypto[r+i]);
f5.getRange(2,numCrypto).setValue(nomiCrypto[r+i]);
}
}
The error:
TypeError: Impossible to find getCell function in the Sheet object
Thanks for your help!
Errors:
getCell() is a method of Range, not Sheet
Google Sheets starts from rowIndex = 1
If you don't need an offset (i.e. start from a certain cell), then you can use getRange:
for (var i = 0; i <= CValue.lenght; i++)
{
var r = i + 1; // rowIndex
CValue[i] = datAgg.getRange(r, 16).getValue();
CName[i] = datAgg.getRange(r+2, 1).getValue();
}
this is the solution:
function regValori() {
var datAgg = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("datiaggiornati");
var f5 = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Foglio5");
var riga = f5.getRange(2, 2).getValue();
for (var i = 2; i <= 6; ++i) {
f5.getRange(riga, i + 1).setValue(datAgg.getRange("P" + i).getValue());
f5.getRange(2, i + 1).setValue(datAgg.getRange("A" + i).getValue());
}
}
i posted another question here for the same problem and I get a perfect answer how to use for loop to drastically reduce code lenght.
the only part I changed is this one: (var i = 2; i <= 6; ++i) with this one: (var i = 2; i <= n+1; ++i), so it can work perfectly with any variable n to get with command "var numCrypto = datAgg.getRange(1,2).getValue();"

Can not save array in shared object as3

I have this code in my simple flash. I want to save name and score in my quiz. My code reference in this website http://www.mollyjameson.com/blog/local-flash-game-leaderboard-tutorial/
I want to make my code in just one actionscript. But I didn't success do it.
var m_FlashCookie = SharedObject.getLocal("LeaderboardExample");
var EntryName:String ="nama kamu";
var EntryScore:String ="nilai";
const NUM_SCORES_SAVED:int = 10;
inputBoxScore.text = EntryScore;
inputBoxName.text = EntryName
var latest_score_object:Object = {
name: EntryName,
score: EntryScore
};
var arr:Array;
arr = m_FlashCookie.data.storedArray
if ( arr == null)
{
arr = new Array();
}
arr.push( latest_score_object );
arr.sortOn("score", Array.NUMERIC | Array.DESCENDING);
if ( arr.length < NUM_SCORES_SAVED )
{
arr.pop();
}
btnSave.addEventListener(MouseEvent.CLICK, saveData);
function saveData(event:Event):void
{
m_FlashCookie.data.arr = arr;
m_FlashCookie.flush();
}
var myHTMLL:String = "";
var total_stored_scores:int = arr.length;
btnLoad.addEventListener(MouseEvent.CLICK, loadData);
function loadData(event:Event):void
{
for (var i:int = 0; i < total_stored_scores; ++i)
{
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var leaderboard_entry:Object = arr[i];
// is this the last score that was just entered last gamestate?
if ( leaderboard_entry == latest_score_object )
{
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ leaderboard_entry.name + " " + leaderboard_entry.score +"</font></b><br>";
}
else
{
myHTMLL += (i+1) + ". "+ leaderboard_entry.name + " " + leaderboard_entry.score +"<br>";
}
}
myHTML.text = myHTMLL;
}
Can anybody help me?
You're saving the array as data.arr but reading the array as data.storedArray. You need to make them the same.
In other words, you've written this:
m_FlashCookie.data.arr = arr;
And when you load:
arr = m_FlashCookie.data.storedArray;
This clearly doesn't make sense: data.storedArray is never set, so it will never have a value, so you will always end up with a new empty array.
You need to use the same property on the shared object data. For example:
m_FlashCookie.data.storedArray = arr;
m_FlashCookie.flush();
Looking at your code, there's a number of other issues:
The latest score is immediately removed because arr.length < NUM_SAVED_SCORES is going to be true from the start, since arr starts out empty, and it then calls arr.pop() which will remove the latest entry that was just added. So the array is always empty.
It adds the score immediately with arr.push(latest_score_object) instead of waiting until the user clicks save, so the value of the input texts don't matter at all -- the saved values will always be "nama kamu" and "nilai".
The following fixes all the issues mentioned:
var leaderboard = SharedObject.getLocal("leaderboard");
const MAX_SAVED_SCORES:int = 10;
inputBoxName.text = "nama kamu";
inputBoxScore.text = "nilai";
var entries:Array = leaderboard.data.entries || [];
var latestEntry:Object;
displayScores();
btnLoad.addEventListener(MouseEvent.CLICK, loadClick);
btnSave.addEventListener(MouseEvent.CLICK, saveClick);
function loadClick(e:MouseEvent):void {
displayScores();
}
function saveClick(e:MouseEvent):void {
saveLatestScore();
displayScores();
}
function saveLatestScore():void {
// create the latest entry based on input texts
latestEntry = {
name: inputBoxName.text,
score: inputBoxScore.text
};
// add the entry and sort by score, highest to lowest
entries.push(latestEntry);
entries.sortOn("score", Array.NUMERIC | Array.DESCENDING);
// if reached the limit, remove lowest score
if (entries.length > MAX_SAVED_SCORES) {
entries.pop();
}
// store new sorted entries to shared object
leaderboard.data.entries = entries;
leaderboard.flush();
}
function displayScores():void {
var myHTMLL:String = "";
for (var i:int = 0; i < entries.length; ++i) {
// loop through every entry, every entry has a "name" and "score" field as that's what we save.
var entry:Object = entries[i];
// is this the last score that was just entered last gamestate?
if (entry == latestEntry)
myHTMLL += (i+1) + ". <b><font color=\"#0002E5\">"+ entry.name + " " + entry.score +"</font></b><br/>";
else
myHTMLL += (i+1) + ". "+ entry.name + " " + entry.score +"<br/>";
}
myHTML.htmlText = myHTMLL;
}

Multidimensional Arrays and one of the fields

There is a multi-d array and I want to reach specific field in it. I have look around it but I was unable to find proper answer to my question.
My array is like that;
array-md
columns-- 0 | 1 | 2
index 0 - [1][John][Doe]
index 1 - [2][Sue][Allen]
index 2 - [3][Luiz][Guzman]
.
.
.
index n - [n+1][George][Smith]
My question is how can I reach only second column of the array? I tried name = array[loop][1]; but it says "Cannot access a property or method of a null object reference". What is the right way to do that?
Here is main part of the code.
get
var lpx:int;
var lpxi:int;
var arrLen:int = Info.endPageArray.length;
for(lpx = 0; lpx < arrLen; lpx++)
{
for(lpxi = Info.endPageArray[lpx][2]; lpxi < Info.endPageArray[lpx][1]; lpxi++)
{
if(Info._intervalSearch[lpxi] == "completed")
{
successCount++;
Info._unitIntervalSuccess.push([lpx, successCount / (Info._intervalSearch.length / 100)]);
}
}
}
set
for(lpix = 0; lpix < arrayLength; lpix++)
{
if(lpix + 1 <= arrayLength)
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix + 1], Info._UnitsTriggers[lpix]]);
}
else
{
Info.endPageArray.push([lpix, Info._UnitsTriggers[lpix], Info._UnitsTriggers[lpix - 1]]);
}
}
Try this:
var tempArr:Array = [];
function pushItem(itemName:String, itemSurname:String):void
{
var tempIndex:int = tempArr.length;
tempArr[tempIndex] = {};
tempArr[tempIndex][tempIndex + 1] = {};
tempArr[tempIndex][tempIndex + 1][name] = {};
tempArr[tempIndex][tempIndex + 1][name][itemSurname] = {};
}
function getNameObject(index:int):Object
{
var result:Object;
if(index < tempArr.length)
{
result = tempArr[index][index + 1];
}
return result;
}
pushItem("Max", "Payne");
pushItem("Lara", "Croft");
pushItem("Dart", "Vader");
//
trace(getNameObject(0));
trace(getNameObject(1));
trace(getNameObject(2));
Multidimensional array is an array of arrays, which you can create like this :
var persons:Array = [
['John', 'Doe'],
['Sue', 'Allen'],
['Luiz','Guzman']
];
var list:Array = [];
for(var i:int = 0; i < persons.length; i++)
{
list.push([i + 1, persons[i][0], persons[i][1]]);
}
trace(list);
// gives :
//
// 1, John, Doe
// 2, Sue, Allen
// 3, Luiz, Guzman
Then to get some data :
for(var j:int = 0; j < list.length; j++)
{
trace(list[j][1]); // gives for the 2nd line : Sue
}
For more about multidimensional arrays take a look here.
Hope that can help.

Resources