user2033475
user2033475

Reputation:

indexOf syntax for multidimensional arrays?

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...

Upvotes: 8

Views: 9326

Answers (5)

dlamblin
dlamblin

Reputation: 45321

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

Upvotes: 3

meder omuraliev
meder omuraliev

Reputation: 186562

x[ x.indexOf(a) ]

This will only work with ordered objects/lists and only if Array.prototype.indexOf is defined.

x = [1,2], b = {one:function(){alert('gj')}}, c = x.push(b);

x[ x.indexOf( b ) ]['one']()

Upvotes: 0

Philippe Leybaert
Philippe Leybaert

Reputation: 171734

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

Upvotes: 1

Ateş G&#246;ral
Ateş G&#246;ral

Reputation: 140032

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

Upvotes: 1

Tim Down
Tim Down

Reputation: 324497

JavaScript does not have multidimensional arrays as such, so x is merely an array. Also, the indexOf method of Array is not supported in all browsers, in particular IE (up to version 7, at least), only being introduced in JavaScript 1.6.

Your only option is to search manually, iterating over x and examining each element in turn.

Upvotes: 0

Related Questions