What is the syntax for indexOf()
to go through a multidimensional array?
For instance:
var x = [];
// do something
x.push([a,b]);
x.indexOf(a) // ??
I want to find 'a
' and do something with 'b
'. But it does not work... As this method should be iterative itself, I do not presume using any other iteration would be a good thing to do. Currently I simulate this using 2 simple arrays but I guess this should somehow work too...
Indexing multi-dimensional arrays Multi-dimensional arrays are indexed in GAUSS the same way that matrices are indexed, using square brackets [] . Scanning above, you can see that the value of the element at the intersection of the third row and second column of x1 is 8.
A multi-dimensional array can be termed as an array of arrays that stores homogeneous data in tabular form. Data in multidimensional arrays are stored in row-major order. The general form of declaring N-dimensional arrays is: data_type array_name[size1][size2]....[sizeN];
You cannot use indexOf to do complicated arrays (unless you serialize it making everything each coordinate into strings), you will need to use a for loop (or while) to search for that coordinate in that array assuming you know the format of the array (in this case it is 2d).
To find the position of an element in an array, you use the indexOf() method. This method returns the index of the first occurrence the element that you want to find, or -1 if the element is not found.
Simply: indexOf()
does not work this way. It might work if you did something like this:
var x = [];
// do something
z = [a,b];
x.push(z);
x.indexOf(z);
But then you'd already have z.b wouldn't you? So if you must ignore the advice of everyone who thinks that using an object (or dictionary) is actually easier you'll have to either use Ates Goral's approach, or search for the index yourself:
Array.prototype.indexOf0 =
function(a){for(i=0;i<this.length;i++)if(a==this[i][0])return i;return null;};
var x = [];
// do something
x.push([a,b]);
x.indexOf0(a); //=> 0
You could use a an object (or dictionary) as Philippe Leybaert suggested. That will allow quick access to elements:
var x = {};
x[a] = b; // to set
alert(x[a]) // to access
But if you insist on using indexOf
, there's still a way, however ugly it is:
var x = [];
var o = Object(a); // "cast" to an object
o.b = b; // attach value
x.push(o);
alert(x.indexOf(a)); // will give you the index
alert(x[1].b); // access value at given index
Unless you want to preserve order, it's much simpler to use a dictionary:
var x = {};
// do something
x[a] = b;
You can still iterate over the keys, although the order is undefined:
for (var key in x) {
alert(x[key]);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With