Page 1 of 1

JavaScript numerical position of value in an array?

Posted: Sat Jan 24, 2009 12:19 am
by JAB Creations
I'm trying to figure out how to determine the numerical position of a value in an array?

In example, I need to determine the position of 'wink' in the smiley array in order to determine which value to select in the smiley_bb array.

Code: Select all

var smiley = ['happy', 'wink'];
var smiley_bb = [':)', ';)'];
I know by looking at it that I want to get the value of '1' so then I can select the two array as smiley_bb[1].

Thoughts please?

Re: JavaScript numerical position of value in an array?

Posted: Sat Jan 24, 2009 2:33 am
by sergio-pro
Hi

You need to iterate through elements, comparing each element with what you are looking for. Once the value matched - you have an index of that element in an array.

BTW you may want to change your structure to JSON - if it simplifies your task. Here how it'll look like

Code: Select all

 
   var smiley = { 'happy' : ':)', 'wink' : ';)' };
 

Re: JavaScript numerical position of value in an array?

Posted: Sat Jan 24, 2009 2:38 am
by JAB Creations
DevNetwork was down just after I figured this out though before I could post. Thanks for your reply, here is what I found...

Code: Select all

var answer = the_array.indexOf('the_value');

Re: JavaScript numerical position of value in an array?

Posted: Sat Jan 24, 2009 2:44 am
by sergio-pro
var answer = the_array.indexOf('the_value');
Unfortunately, this wont work in IE

Re: JavaScript numerical position of value in an array?

Posted: Sat Jan 24, 2009 6:36 am
by VladSun
The easiest way:
[js]var bb_mapper = {    happy  : ':)',     wink   : ';)'};[/js]

It will create an object with happy and wink properties having values ':)' and ';)' accordingly.
Then addressing a property is easy:
[js]alert(bb_mapper.happy);// or a more useful way for youalert(bb_mapper['happy']);[/js]
It's fast because no search operations are performed.

Re: JavaScript numerical position of value in an array?

Posted: Sat Jan 24, 2009 6:28 pm
by Chris Corbyn
JSON++

Re: JavaScript numerical position of value in an array?

Posted: Sun Jan 25, 2009 6:32 am
by VladSun
Chris Corbyn wrote:JSON++
Why? It's locally stored data, so it could be implemented with "static-like" JS object, without playing with JSON coding.

Re: JavaScript numerical position of value in an array?

Posted: Sun Jan 25, 2009 8:13 am
by Chris Corbyn
VladSun wrote:
Chris Corbyn wrote:JSON++
Why? It's locally stored data, so it could be implemented with "static-like" JS object, without playing with JSON coding.
I should have said object-literal. I just meant don't use an array when you want to map named keys to values :oops:

JSON (a.k.a JavaScript Object Notation) is basically the same as a JavaScript object, so I always just call it JSON even when I'm not referring to the string form for transportation.