RefMa77
RefMa77

Reputation: 293

How can I set/assign an Array in a two dimensional Array

I´d like to describe my probblem in the code:

//Master-Array
var dependenceArray:Array = new Array();

//Array for IDs 
var idArray:Array = new Array(1,3,5,6,7);

//Array with IDs and dependeces
var rowArray:Array = new Array(idArray,"dependence1","dependence2");
dependenceArray.push(rowArray)


//Next pair
idArray = new Array(0,1,2,3);
rowArray = new Array(idArray,"dependence1","dependence2");
dependenceArray.push(rowArray);

Now it looks like this:

enter image description here

So how can I get to every single Value? How can I assigne Dependence1 or Dependence2 and how do I get every Single ID in the ID colum. For example, I want to know if ID = 0 is part of IDs in row 1?

Thank you in advance

Upvotes: 0

Views: 56

Answers (2)

Pranav Negandhi
Pranav Negandhi

Reputation: 1624

Your value columns can be accessed using the following syntax.

var val:String = dependenceArray[0][1]; // "Value1.0"

The first bracket accesses the row, and the second accesses the column.

To check whether the IDs column contains a value, use the .indexOf() method on the first column.

var contains:int = (dependenceArray[0][0] as Array).indexOf(5); // returns 1
contains:int = (dependenceArray[0][1] as Array).indexOf(5); // returns -1

Upvotes: 2

null
null

Reputation: 5255

You are explicitly naming the elements in your arrays and you want to identify them by the given name. That's why using arrays is not a good solution.

Instead, use an object per row.

//Master-Array
var dependenceArray:Array = []; // equivalent to new Array();

//Object with IDs and dependeces
var rowObject:Object = {ids:[1,3,5,6,7],dependencies:["Value 1.0", "Value 2.0"]};
dependenceArray.push(rowArray)


//Next pair
rowObject:Object = {ids:[0,1,2,3],dependencies:["Value 1.1", "Value 2.1"]};
dependenceArray.push(rowArray);

This allows for a much more readable code, because you can use the names of the properties to access them:

trace(dependenceArray[0].ids);

As you can see above, I used an array for the ids and the dependencies. Generally speaking, whenever you use names with a number at the end to distinguish them, you should use an array instead.

I also use the shorthand notation [] for arrays.

Conclusion: You have many rows. That's why using an array to store all rows is a good idea. Each row however, has named properties, which makes an Object a more appropriate choice to store the information of a single row. The values of the properties of a row are lists again (a list of ids and a list of dependencies) so using Array is the better option.

Upvotes: 1

Related Questions