473,385 Members | 1,325 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

Index of an array entry

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.

Mar 24 '06 #1
6 2218
ro*******@gmail.com 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.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Javascript Best Practices - http://www.JavascriptToolbox.com/bestpractices/
Mar 25 '06 #2
ro*******@gmail.com wrote:
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.
--
Rob
Mar 25 '06 #3
Thanks for the very thorough response, Rob.

Mar 25 '06 #4
//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!

Mar 25 '06 #5
//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] ];}

Mar 25 '06 #6
/* 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

Mar 25 '06 #7

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: jerrygarciuh | last post by:
Hello, In reading through the list of array-related functions I did not find on which returns the numeric index where the array's internal pointer currently sits. Is there such a function? ...
1
by: Gustaf Liljegren | last post by:
Hi, I've been struggling with this for days now. Hope to get some help here, but some knowlegde in XML is required. I'm trying to create a back-of- book index in XML, following this DTD: ...
7
by: Stefan Mueller | last post by:
I choose 'Entry 4' and click then on the button 'Set' to set the index to 'Entry 2'. If you press now the cursor down key 'Entry 5' instead of 'Entry 3' shows up with Mozilla Firefox. With Internet...
4
by: Fir5tSight | last post by:
Hi, I declare PageObjectsArray1 and PageObjectsArray2 as ArrayList. Each element in the array is a Page object. Now I want to compare every pair of Page objects of the same index in the two...
8
by: Joe Rattz | last post by:
Ok, I can't believe what I am seeing. I am sure I do this other places with no problems, but I sure can't here. I have some code that is indexing into the ItemArray in a DataSet's DataRow. I...
7
by: d d | last post by:
I have an array of objects that start out looking like this: var ra=; I want to be able to access the array by index number from some code, and by the name property from other code, as if it...
0
by: anuptosh | last post by:
Hi, I have been trying to run the below example to get a Oracle Array as an output from a Java code. This is an example I have found on the web. But, the expected result is that the code should...
4
by: student4lifer | last post by:
If I have a multidimentional array that contains many arrays inside as follows: $voters=array(array('name'=>'Joe', 'profession'=>'blumbing', 'state'=>'Ohio'), array('name'=>'Obama',...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.