Index of an array entry

R

routeslip

I'm refering to an entry in an array by it's string key, as in
foo["bar"]. Is there a way to get the numeric index of that array
without iterating through the entire array?

What I need to do is find the "next" or "previous" entry in the array,
but the keys are strings, instead of numerical indeces.

thanks for your help.
 
R

RobG

I'm refering to an entry in an array by it's string key, as in
foo["bar"]. Is there a way to get the numeric index of that array
without iterating through the entire array?

That property doesn't have an index. If you add a property to an array like:

var foo = new Array();
foo['bar'] = 'some value';
alert(foo.length); // Shows '0'

you have added a property to the array object just like you have to any
other common object - arrays are objects with a special length property and
a few built-in methods, otherwise they are just objects. The only 'order'
that such properties have is the order in which they are added to the object.

The only way to read them in any sort of order is using for..in, and I
don't think that is guaranteed to return them in the order they were added
(though it may very well do so in most cases). The spec sect 12.6.4 says:

"The mechanics of enumerating properties ... is implementation
dependent. The order of enumeration is defined by the object."

Try this:

var foo = [];
foo[foo.length] = 'zero';
foo['bar'] = 'one';
foo['1'] = 'two';
foo['10'] = 'three';
foo['bob'] = 'four';
foo['5'] = 'five';
for (var p in foo){
alert(foo[p]);
}

I get: one, four, zero, two, five, three in Safari,

and: zero, one, two, three, four, five in Firefox and IE.

If you were to use for..in to find 'two', then look for the property with
the next highest index, you'd get back 'undefined'. If you keep going up
the indexes until you find one that is defined, you'll get 'five'.

The next value returned after 'two' in the for..in series is either 'five'
or 'three', depending on the browser.

What I need to do is find the "next" or "previous" entry in the array,
but the keys are strings, instead of numerical indeces.

The special properties of an array are only useful if you use numeric
indexes (remembering that all property names, including numeric indexes,
are stored as strings). If you aren't using any numeric indexes, then you
should use a plain object and adding your own methods to create an order
and indexes.
 
R

Randy Webb

(e-mail address removed) said the following on 3/24/2006 6:14 PM:
I'm refering to an entry in an array by it's string key, as in
foo["bar"]. Is there a way to get the numeric index of that array
without iterating through the entire array?

bar does not have a "numeric index" as it's not truly an array entry but
rather it is a property of the array.
What I need to do is find the "next" or "previous" entry in the array,
but the keys are strings, instead of numerical indeces.

You could use for-in to loop through the array and build a new -
numerically indexed - array and then use a "next" and "previous" entry.
 
A

AndrewTK

//Assume the associative array:

meals["fish"] = "kipper";
meals["pasta"] = "spagbol";
meals["curry"] = "tandoori";
meals["meat"] = "tartare";

// There are no indexes, there are keys.
// get an array of keys

k = new Array(0);
for(i in meals) {
k[k.length] = i;
}

k.sort(); // to sort the keys alphabetically, not required, can be
useful
// otherwise there is no contract as to whether
// the keys will be returned in insertion order or not

// You can thus get the items in defined order and via numeric index
meals[ k[x] ];

/*
Try otherwise a data type: the following can be passed an associative
array. Calling ietm( number ) gets the corresponding item. calls to
next() and prev() do what you'd expect

You could improve on this by, say, getting the internal index number to
loop, or do something appropriate on reaching start or end, check the
requested index is not out of bounds etc */

function Iterator(src_array) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;

for(var i in internal) {
keys[keys.length] = i;
}
}

function getnextitem() {return this.internal[ this.keys[i++] ];}

function getprevitem() {return this.internal[ this.keys[i--] ];}

function getitem(idx) {
this.i = idx;
return this.internal[ this.keys[idx] ];
}

function getisize(idx) {return this.internal.length;}

Iterator.prototype.next = getnextitem;
Iterator.prototype.prev = getprevitem;
Iterator.prototype.item = getitem;
Iterator.prototype.size = getsize;

// === example of use:

mealiterator = new Iterator(meals);
document.write(mealiterator.item(2) );
document.write(mealiterator.next() );
document.write(mealiterator.next() );

// Good luck, and bon apétit!
 
A

AndrewTK

//correction:
// some functions were not quite correct. below they are corrected

function Iterator(src_array) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;

for(var n in internal) {
keys[keys.length] = n;
}

}

function getnextitem() {return this.internal[ this.keys[++this.i] ];}

function getprevitem() {return this.internal[ this.keys[--this.i] ];}
 
A

AndrewTK

/* To those who think they saw this before:
I have deleted my previous posts. this is a new post with
code that actually works (!)

The importance of testing code before publishing :)
*/

//Assume the associative array:

meals = new Array(0);
meals["fish"] = "kipper";
meals["pasta"] = "spagbol";
meals["curry"] = "tandoori";
meals["meat"] = "tartare";

// There are no "indexes", there are "keys".
// get an array of keys:

k = new Array(0);
for(i in meals) {
k[k.length] = i;

}

k.sort(); // to sort the keys alphabetically, not required, can be
useful
// otherwise there is no contract as to whether
// the keys will be returned in insertion order or not

// You can thus get the items in defined order and via numeric index
meals[ k[3] ];

/*
Try otherwise a data type: the following can be passed an associative
array, to get a data type that holds the array and can be iterated over
with function calls, with the option of sorting the keys. Calling item(
number ) gets the corresponding item. calls to next() and prev() do
what you'd expect

On calling prev() or next() at the start or end respectively of the
array will return null and the counter will be reset to the opposite
end of the array, and return null.

(see further for example of use)

*/

function Iterator(src_array,sorting) {
this.keys = new Array(0);
this.internal = src_array;
this.i = 0;

for(var n in this.internal) {
this.keys[this.keys.length] = n;
}

if(sorting) {this.keys.sort();}
}

function getnextitem() {
++this.i;
if( this.i >= this.keys.length ) {this.i = -1;return null;}
return this.internal[ this.keys[this.i] ];
}

function getprevitem() {
--this.i;
if( this.i < 0 ) {this.i = this.keys.length;return null;}
return this.internal[ this.keys[this.i] ];
}

function getitem(idx) {
if( idx >= this.keys.length || idx < 0 ) {return null;}
this.i = idx;
return this.internal[ this.keys[idx] ];
}

function getsize() {return this.keys.length;}

Iterator.prototype.next = getnextitem;
Iterator.prototype.prev = getprevitem;
Iterator.prototype.item = getitem;
Iterator.prototype.size = getsize;

// === example of use:

mealiterator = new Iterator(meals,true);
document.write(mealiterator.item(2)+", " );// tartare
document.write(mealiterator.next()+", " );// spagbol
document.write(mealiterator.next()+", " );// null
document.write(mealiterator.next()+"<br>" );// tandoori (we are back at
the start)

document.write(mealiterator.item(1)+", " );// kipper
document.write(mealiterator.prev()+", " );// tandoori
document.write(mealiterator.prev()+", " );// null
document.write(mealiterator.prev()+"<br>" );// spagbol - back at end
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top