How do I split a text into different values? - arrays

I want to split the inputted data then check each line so if it's a number it gets pushed into the score Array and if not then it gets pushed into the name Array. I'm new and I have no idea what I'm doing. so far I have this :
var lines:Array = String(event.target.data).split(":");
var linesNum:int = lines.length;
for(var i:int = 0 ; i < linesNum; i++){
trace('line ' + i + ': ' + lines[i]);
var scores:Array = [];
for (var i:int; i < lines.length; i++) {
scores.push(lines[i]);
}
classone_import.text = (scores.sort());

I recommend you to use regular expressions.
var str:String = "*Test B:10 *Test A:0 *Test C:7";
var wordsRe:RegExp = /\w+ \w+/g; // word + space + word
var valuesRe:RegExp = /\d+/g; // only digits
var names:Array = str.match(wordsRe);
var scores:Array = str.match(valuesRe);
trace(names);//Test B, Test A, Test C
trace(scores);//10, 0, 7

Does this suit your needs?
var s:String = "*Test B:10 *Test A:0 *Test C:7";
var divider:String = "*"; //the divider is "*" - taken from your example
var arr:Array = s.split(divider); //split the string by the specified divider
var scores:Array = [];
var names:Array = [];
for(var i:int=0; i<arr.length; i++) {
if(arr[i] == "") continue; //I am not sure whether this will occur but as your string begins with *, the first item may be "" -> so skip that
var item:Array = arr[i].split(":"); //split the string to 'name', 'score'
names.push(item[0]);
scores.push(parseFloat(item[1])); //parse the number from string; you could use parseInt if all the numbers are integers for sure
}
Then you can sort it or whatever you intend to do with it.

Related

Google Script array value undefined

i wrote a code that should take a value from a cell and than convert it to the string and than into the array. its working fine. I can see the value of arr in Logs as an array with the input of the cell. For example, in the cell are " dog, cat " and tha arr value in Logs is [dog, cat].
But after i create this array, i would like to make a loop on it. And than i become in Logs, that arr is undefined. Can somebody help me please? im working on it for 2 days :(
Here is my code:
function animal (s,z){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var range = sheet.getRange("SM");
var columnNumber = getColumnNumberOfSM(s);
var rowNumber = getRowNumberOfSM(z);
var colAction = columnNumber + 1;
var action = sheet.getRange(rowNumber, colAction, 1, 1).getValues();
var bar = action.toString();
var arr = [{}];
arr = bar.split(", ");
//return arr; // returns an array [dog, cat]
var foo = arr; // underfined
for (var i = 0; i <= foo.length; ++i) {
if (foo[i] == "dog") {
Logger.log(upload());
}
}
}
now i edit my code and its working fine,but only with "dog" but not with "cat"
function animal(){
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheetByName('Sheet1');
var action = sheet.getRange("C3").getValue();
var bar = action.toString();
var arr = bar.split(", ");
for (var i = 0; i <= arr.length; ++i) {
if (arr[i] == "dog") { // works
Logger.log(upload());
}
if (arr[i] == "cat") { // doesn't work
Logger.log(upload());
}
}
}
You don't need to initiate arr as blank you can directly initialize it as a result to split method , also one point I didn't get is why do you need to assign arr to foo? You can directly iterate through arr.length and perform the required operation.
Here's my working snippet.
var parts = path.split(",");
for (var i = 0; i < parts.length; i++) {
if (parts[i] == 'dog'){
Logger.log(parts[i]);
}
}

Remove movieClips using array list?

I've a array of list and created image place holder with the array objects name (Example: myArray[a,b]) and loaded images from there, having array list as folder name.
And finally created a movieClip to load on them and display in stage.
Now I want to remove them calling the same array list.
Need help here...
My code below:
for (var l: int = 0; l < ListArray.length; l++) {
var BookName: MovieClip = new bookThumb();
trace("\n[" + l + "]: " + ListArray[l]);
ImageFoldername = ListArray[l];
var bookImagePath: String = "file://" + File.userDirectory.nativePath.toString() + "/Books/" + ImageFoldername + "/Images/Icon.png";
trace(bookImagePath);
var ImagePlacer: Loader = new Loader;
var ImageURL: URLRequest = new URLRequest(bookImagePath);
ImagePlacer.load(ImageURL);
BookName.addChild(ImagePlacer);
BookName.name = ImageFoldername
addChild(BookName)
BookName.x = FirstBook_x;
BookName.y = FirstBook_y;
BookName.buttonMode = true;
BookName.mouseChildren = false;
BookName.addEventListener(MouseEvent.CLICK, IconSelected);
BookName.alpha = .8
BookName.addEventListener(MouseEvent.MOUSE_OVER, IconMouseOver);
BookName.addEventListener(MouseEvent.MOUSE_OUT, IconMouseOut);
FirstBook_x = FirstBook_x + 250;
}
Because you assign the ImageFoldername to each MovieClip's name property, you can use getChildByName to find them and remove them:
(Note: convention in AS3 is to use UpperCamelCase for classes, and lowerCamelCase for variables and functions. I've written the code below following this convention. )
for (var i:int = 0; i < listArray.length; i++) {
var imageFolderName:String = listArray[i];
var bookThumb:BookThumb = getChildByName(imageFolderName) as BookThumb;
if (bookThumb) {
removeChild(bookThumb);
}
}
Another way you can handle it is to add each book thumb into a list:
var bookThumbs:Array = [];
for (var i:int = 0; i < listArray.length; i++) {
var bookThumb:Bookthumb = new BookThumb();
bookThumbs.push(bookThumb);
// ...
}
Then to remove them all:
for each (var bookThumb:BookThumb in bookThumbs) {
removeChild(bookThumb);
}
bookThumbs.length = 0;
But probably the easiest way to remove them all would be to simply put them all in a single container and later use removeChildren() to remove them all:
var container:Sprite = new Sprite();
addChild(container);
for (var i:int = 0; i < listArray.length; i++) {
var bookThumb:Bookthumb = new BookThumb();
container.push(bookThumb);
// ...
}
// when you want to remove them all:
container.removeChildren();

how to search for a specific word in a huge array?

In AS3 :
I've got a long text in an array.
var myHugeArray:Array = ["I love Apple
I have an Iphone
I eat a Banana
I'm John
I sell a computer
I sell an Apple
I love rock
I sell a car"];
How can I do to search a specifics words ? (like : show me sentences with the word "apple") --> output : "I love Apple" and "I sell an Apple"
Thanks,
EDIT
Here's what I did so far :
loader5.load(urlReq);
loader5.addEventListener(Event.COMPLETE,completeHandler2);
function completeHandler2(event:Event):void{
loader5.removeEventListener(Event.COMPLETE,completeHandler2);
trace("Données envoyées");
feedbackText.text = "Données envoyées";
loader5.load(urlReq);
loader5.addEventListener(Event.COMPLETE, complete);
}
function complete(e:Event):void {
addChild(list);
products = JSON.parse(loader5.data) as Array;
feedbackText.text = "complete";
for(var i:int = 0; i < products.length; i++){
createListItem(i, products[i]);
}
showList();
}
function createListItem(index:int, item:Object):void {
var listItem:TextField = new TextField();
listItem.text = item.title;
listItem.addEventListener(MouseEvent.CLICK, function(e:MouseEvent):void {
showDetails(item);
});
list.addChild(listItem);
str = item.title;
bar();
}
function bar(){
var arr: Array ;
searchBar.type = TextFieldType.INPUT;
var suggested:Array = new Array();
var textfields:Array = new Array();
searchBar.addEventListener(Event.CHANGE, suggest);
arr = str.split(",");
trace(arr);
function suggest(e:Event):void
{
suggested = [];
for (var i:int = 0; i < textfields.length; i++)
{
removeChild(textfields[i]);
}
textfields = [];
for (var j:int = 0; j < arr.length; j++)
{
if (arr[j].indexOf(searchBar.text.toLowerCase()) != -1)
{
var term:TextField = new TextField();
term.width = 360;
term.height = 24;
term.x = 18;
term.y = (24 * suggested.length) + 135;
term.border = true;
term.borderColor = 0x353535;
term.background = true;
term.backgroundColor = 0xFF9900;
term.textColor = 0x4C311D;
term.defaultTextFormat = format;
addChild(term);
suggested.push(arr[j]);
term.text = arr[j];
}
}
function showList():void {
list.visible = true;
}
function showDetails(item:Object):void {
titleTxt.htmlText = item.title;
detailsTxt.htmlText = "<U>prix:</U> " + item.prix + " xpf"+ "\n\n<U>Description:</U> " + "\n"+item.theDescription + "\n"+"\n\n<U>Contact:</U> " + item.mail+ "\n"+item.phone;
}
So, my AS3 code go search for PHP variable with loader5.
All the items found by the php are put in an Array (products).
And a list of all the products is created. (createListItem).
If I click on an item, it show me some details (price, description..etc). It's the function showDetails();
Know I've created a searchBar (autocomplete).
An array is created (arr) that split the string (str).
Then it does what it does to search through the array.
Problems :
1/ Weirdly, not all the words are displayed in my searchBar. Some words are working, other not.
2/ How can I do to call the function showDetails() when the user click on the suggest term ? (term.addEventListener(MouseEvent.CLICK, showDetails)); doesn't work as the terms is not item.title. ShowDetails is showing details of item.title. (so how can I say that term = item.title ?)
3/ Do you see a way simpler than that ?
Your myHugeArray is just string, so split() it with \n', you got the
ret array for example, then find the one contains the word you search, like "apple", using indexof() in each string
You need to split the string into an array then search each item
check this out
https://stackoverflow.com/a/34842518/3623547

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;
}

Google Apps Scrit add value to array every time a loop executes

I would like to add "RealData" to my array "tempArr", I am trying to use "push" but I have no experience with it so I can not get it to work. Could you help me out?
for (var i=0; i < data.length; i++) {
var testDate = subDaysFromDate(data[i][0],1)
var DateToCheck = Utilities.formatDate(testDate, "GMT", "dd-MM-yyyy");
var DateToCheckBefore = DateToCheck.split("-");
var DateToCheckAfter = new Date(DateToCheckBefore[2], DateToCheckBefore[1]-1, DateToCheckBefore[0]); //dit is de datum van een row
Row++;
var tempArr = new Array();
var d1 = $d1.split("-");
var d2 = $d2.split("-");
var from = new Date(d1[0], d1[1]-1, d1[2]); // -1 because months are from 0 to 11
var to = new Date(d2[0], d2[1]-1, d2[2]);
if(DateToCheckAfter >= from && DateToCheckAfter <= to){
var KlantNr = sheet.getRange("A"+Row).getValue();
var KlantVoornaam = sheet.getRange("B"+Row).getValue();
var KlantAchternaam = sheet.getRange("C"+Row).getValue();
var HTMLData = KlantNr + "-" + KlantVoornaam + "-" + KlantAchternaam;
var RealData = HTMLData.split("-");
tempArr.push(RealData);
}
}
Logger.log(tempArr);
When you PUSH an array into another you're referencing it, to copy use slice:
tempArr.push(RealData.slice(0));
Also, this is a javascript problem.

Resources