Seeking a way to merge arrays by index like so:
var a1:Array = ["a", "b", "c"];
var a2:Array = ["1", "2", "3"];
var a3:Array = result: ["a", 1, "b", 2, "c", 3]
I've tried concat, push, splice... not getting close. Thanks.
function arrayMerge(arr1:Array, arr2:Array):Array {
var o:Array = new Array();
for (var i:int=0; i<Math.max(arr1.length, arr2.length); i++) {
if (i<arr1.length) o.push(arr1[i]);
if (i<arr2.length) o.push(arr2[i]);
}
return o;
}
Thanks Payam for answer and non-judgement. Here's how I applied your work:
var arr1:Array = ["question1", "question2", "question3"];
var arr2:Array = ["answer1", "answer2", "answer3"];
var o:Array = new Array();
for (var i:int=0; i<Math.max(arr1.length, arr2.length); i++) {
if (i<arr1.length) o.push(arr1[i]);
if (i<arr2.length) o.push(arr2[i]);
}
trace(o); //(question1,answer1,question2,answer2,question3,question3)
#AndyH :
payamsbr is right, but you may work with Vectors or Arrays
Perhaps tl; dr; but this is the principle.
If You want to understand something try those possibilities.
If you don't, just copy and paste some shorter code ;)
var v1:Vector.<String> = new <String>["a", "b", "c"];
var v2:Vector.<uint> = new <uint>[1, 2, 3]; // why do you use String here and not uint?
// if you want to convert a uint to a String, use myUint.toString();
function convertVectorToArray(v1:Vector.<String>,v2:Vector.<uint>):Array{
var mergedArray:Array = new Array();
if (v1.length != v2.length){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same lenfgth!"));
}else{
for(var i:uint = 0; i <v1.length ; i++){
mergedArray.push(v1[i]);
mergedArray.push(v2[i]);
}
}
return(mergedArray);
}
function mergeVectors(v1:Vector.<String>,v2:Vector.<uint>):Vector.<Object>{
var mergedVector:Vector.<Object> = new Vector.<Object>();
if (v1.length != v2.length){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}
for(var i:uint = 0; i <v1.length ; i++){
mergedVector.push(v1[i] as String);
mergedVector.push(v2[i] as uint);
}
return(mergedVector);
}
var mergedArray:Array = (convertVectorToArray(v1,v2));
var mergedVector:Vector.<Object> = (mergeVectors(v1,v2));
function listArray(arr:Array):String{
var str: String="";
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < arr.length ; i++){
str+="typeof(arr[" + i + "]) = " + (typeof(arr[i]) as String).toUpperCase() + ", value = " + arr[i] + "\n";
}
}
return str;
}
function listVector(vect:Vector.<Object>):String{
var str: String = "";
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < vect.length ; i++){
str+="typeof(vect[" + i + "]) = " + (typeof(vect[i]) as String).toUpperCase() + ", value = " + vect[i] + "\n";
}
}
return str;
}
trace(listArray(mergedArray));
trace(listVector(mergedVector));
You may add a sort() method if You need it (you didn't told about it)
And Always throw an Error if the 2 Arrays or Vectors don't have the same length!
Throwing an Error is the best way to understand if something goes wrong...
This will avoid You a lot of time if You need to debug Your code!!!
As You can see the output is the same, but if the Vector Class is used correctly, this is more efficient than an Array.
Output :
Since there's a Vector Class, I don't understand a lot of people who chose Arrays instead...
Of course Vector. is a nonsense, but I posted it anyway so You can figure You out the Vector Class.
Output is the same :
typeof(arr[0]) = STRING, value = a
typeof(arr[1]) = NUMBER, value = 1
typeof(arr[2]) = STRING, value = b
typeof(arr[3]) = NUMBER, value = 2
typeof(arr[4]) = STRING, value = c
typeof(arr[5]) = NUMBER, value = 3
typeof(vect[0]) = STRING, value = a
typeof(vect[1]) = NUMBER, value = 1
typeof(vect[2]) = STRING, value = b
typeof(vect[3]) = NUMBER, value = 2
typeof(vect[4]) = STRING, value = c
typeof(vect[5]) = NUMBER, value = 3
I forgot this easiest way if you really want an Array...
Quick done!
var ar1:Array = [1,2,3];
var ar2:Array = ["a","b","c"];
function merge(...arrays):Array {
var result:Array = [];
for(var i:int=0;i<arrays.length;i++){
result = result.concat(arrays[i]);
}
return result;
}
trace(merge(ar1, ar2));
// outputs : 1,2,3,a,b,c
Another possibility :
function populateObject(v1:Vector.<String>, v2:Vector.<uint>):Object{
var obj = new Object();
if ((v1.length*2) != (v1.length + v2.length)){
throw(new Error(" ***ERROR : the two Vectors or Arrays have not the same length!"));
}else{
for (var i:uint = 0; i < v1.length; i++){
obj[v2[i]] = v1[i];
}
}
return obj;
}
var o:Object = populateObject(v1,v2);
function listObject(someObj:Object):void{
var myObj:Object = someObj;
for (var i:String in someObj){
trace(someObj[i] + ": " + i);
}
}
listObject(o);
output =
a: 1
b: 2
c: 3
I think that You have a lot of possibilities to use here even it's my longer answer ;)
If You try those possibilities and understand them, this will certainty help You to think to find the best way to deal with Your issue.
But You may also copy and paste some shorter code.
I just wanted to show You that there's more than one answer.
If you understand this, You will be able to go further with coding.
Have fun ;)
Sincerely.
Nicolas
Best regards.
Nicolas.
Related
Is there? Like Let's say I need 5 variables in ActionScript 3.0 and would like to name them as follows:
var myVar_1 = "things";
var myVar_2 = "things";
var myVar_3 = "things";
var myVar_4 = "things";
var myVar_5 = "things";
But instead of having to type them 1 by 1, would it work in a loop? I can't seem to make it work and would really love some help/advice on this matter.
Yes, you can create a dynamic property name using [ ] array access:
var variables:Object = {};
for(var i:int = 0; i < 5; i++){
variables["myVar" + i] = "value " + i;
}
trace(variables.myVar3); // "value 3"
The variables object in this case could be replaced by any dynamic object, including MovieClips.
However, in most cases to store data by index it usually makes more sense to use an array. Example:
var variables:Array = [];
for(var i:int = 0; i < 5; i++){
variables.push("value " + i);
}
trace(variables[3]); // "value 3"
You should use Vector.<String>, Array, Object or Dictionary for that:
var variables:Vector.<String> = new <String>[];
for(var i:int = 0; i<5; i++)
{
variables[i] = "things";
}
I'm not entirely sure if this is possible at all, but I'm trying to take a string in Flash and check to see if it is the same as the name of an already existing variable. Here is a piece of my code:
var randomNumber:int;
var randomNumberS:String;
var Mem1:String;
var Mem2:String;
randomNumber = Math.floor(Math.random()*3);
randomnumberS = ("Mem" + String(randomNumber));
TGiven.text = [the randomnumberS string, except as either the variable name Mem1 or Mem2]
Is this a possible task, and if not, is there a better way to perform this task? It would be very useful as I plan on making many more variables that start with Mem with higher and higher numbers.
It would be optimal if the variables were a member of a class or Object, to which you could evaluate whether they exist using hasOwnProperty().
For example:
var obj:Object = {
Mem1: "value1",
Mem2: "value2"
};
You could test whether obj has a property by name:
obj.hasOwnProperty("Mem1");
Applying your example using random numbers:
for (var i = 0; i < 100; i++) {
var randomNumber:int = Math.floor(Math.random() * 3);
if (obj.hasOwnProperty("Mem" + randomNumber))
trace("Mem" + randomNumber + " exists.");
else
trace("Mem" + randomNumber + " does not exist.");
}
You can also use the in keyword, such as:
"Mem1" in obj;
Using the same example:
for (var i = 0; i < 100; i++) {
var randomNumber:int = Math.floor(Math.random() * 3);
if (("Mem" + randomNumber) in obj)
trace("Mem" + randomNumber + " exists.");
else
trace("Mem" + randomNumber + " does not exist.");
}
Currently the way that I am taking a JSON string where I "Don't know the contents" and pulling the keys and the values is as follows:
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var arrLen = arr.length;
for(var i = 0; i < arrLen; i++){
var myKeys = Object.keys(arr[i]);
var keysLen = myKeys.length;
for(var x = 0; x < keysLen; x++){
keyName = myKeys[x];
keyValueStr = "arr[i]."+keyName;
keyValue = eval(keyValueStr);
console.log(keyName+':'+keyValue);
}
}
There has to be a cleaner and more efficient way of doing this. Any suggestion would be appreciated.
Using jQuery you can use http://api.jquery.com/jQuery.parseJSON/ & Object.keys - Than:
var obj = jQuery.parseJSON('{"manager_first_name":"jim","manager_last_name":"gaffigan"}');
var keys = Object.keys(obj);
jQuery.each(keys,function(k, v){
console.log(v);
console.log(obj[v]);
});
Create an object and initialize it with your JSON:
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
var JSONObject = new MyJSONObject(arr);
in your constructor, set the object's properties.
You could use for-in loop which iterates over the enumerable properties of an object, in arbitrary order.
var arr = [{"manager_first_name":"jim","manager_last_name":"gaffigan"}];
for (var i = 0; i < arr.length; i++) {
var currentObj = arr[i];
for (var item in currentObj) {
console.log(item + " : " + currentObj[item]);
}
}
If your array always have only one item, you could omit the outermost for loop and just use arr[0]
var currentObj = arr[0];
for (var item in currentObj) {
console.log(item + " : " + currentObj[item]);
}
I have the following object:
var users:Object= new Object();
users[0]["user_id"] = "1124";
users[0]["name"] = "ikke";
users[0]["age"] = "24";
users[0]["gender"] = "male";
users[1]["user_id"] = "1318";
users[1]["name"] = "test";
users[1]["age"] = "20";
users[1]["gender"] = "male";
var selectors:Object = new Object();
selectors["user_id"] = 1318;
selectors["gender"] = "male";
what i want is to use the selectors object in an if statement. In humans lanuguage it should be something like:
for (var index:String in users) {
If users[index]["gender"] == selectors[gender] && users[index]["user_id"] == "male" -> then trace "success".
}
The tricky part is that the selectors object is dynamic. Sometimes it can contain only 1 item , sometimes 3 items. Or it can also be null. In that case it should allways trace success. Anyone that can help me?
for(var i:int = 0; i < users.length; i++) {
var success:Boolean = true;
for(var key:String in selectors) {
if(users[i][key] != selectors[key]) {
success = false;
break;
}
}
if(success) {
trace('success for user ' + i);
}
}
I've been working on a project for a while but got stuck where I have a text file that contains a set of numbers in this format:
1-2-3-4
1-2-3-4
1-2-3-4
1-2-3-4
So I must read the numbers from the file and put them in an array according to the column so at the end I have
column1:Array (1,1,1,1)
column2:Array (2,2,2,2)
..... and so on. I can't figure how to do this.
What I managed to do was read all the file and have all the numbers in 1 array but just that.
Here's the code
var myTextLoader:URLLoader = new URLLoader;
var txtArray:Array;
myTextLoader.load(new URLRequest(inputFile.text));
myTextLoader.addEventListener(Event.COMPLETE,onLoaded);
function onLoaded(e:Event):void
{
txtArray = e.target.data.split(/\-|\n/g);
}
before split \n \r to array (reading with a loop)
and the same with... -
a loop in loop to get a multidimensional array
in mind the result is a "table"
finally to get a result do this.
variable[file][column]
a[2][3] ----> 4
;)
Try splitting it into two parts, first by line, then by element:
function onLoaded(e:Event):void
{
preArray:Array = e.target.data.split(/\n/g);
txtArray = new Array();
for(var i:int = 0; i < preArray.length; i++) {
txtArray.push(preArray[i].split(/\-/g));
}
}
This will give you a 2D array, which you'd access like this:
textArray[0][0]; // result: 1
textArray[2][3];
Et cetera.
Thanks to Llanis who gave me the idea. This is my final code. Sorry i didn't tag the language it never ocurred to me i'm new.
myTextLoader.load(new URLRequest(inputWX.text));
myTextLoader.addEventListener(Event.COMPLETE,onLoaded);
function onLoaded(e:Event):void
{
txtArray = e.target.data.split(/\-|\n/g);
var wArray:Array = new Array(txtArray.length/4);
var xArray:Array = new Array(txtArray.length/4);
var yArray:Array = new Array(txtArray.length/4);
var zArray:Array = new Array(txtArray.length/4);
var a:int = 0;
var b:int = 0;
var c:int = 0;
var d:int = 0;
var columna:int = 1;
for(var arrayIndex:int = 0; arrayIndex <= txtArray.length-1;arrayIndex++)
{
switch(columna){
case 1: wArray[a] = txtArray[arrayIndex]; a+=1;
break;
case 2: xArray[b] = txtArray[arrayIndex]; b+=1;
break;
case 3: yArray[c] = txtArray[arrayIndex]; c+=1;
break;
case 4: zArray[d] = txtArray[arrayIndex]; d+=1;
break;
}
if(columna == 4)
columna = 1;
else columna++;
}
}