Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of the associative array in JavaScript by key and access by index

I have an associative array like:

var arr = {};
arr['alz'] = '15a';
arr['aly'] = '16b';
arr['alx'] = '17a';
arr['alw'] = '09c';

I need to find the previous and next key of any selected element. Say, for key 'aly' it will be 'alz' and 'alx'. If possible, I want to access the array by index rather than the key.

Currently, I am doing this using a separate array containing keys, e.g.

var arrkeys = ['alz','aly','alx','alw'];
like image 995
biztiger Avatar asked Dec 09 '25 22:12

biztiger


2 Answers

Ordering of the object's properties is undefined. You can use this structure...

[{ key: 'alz', value: '15a'},
 { key: 'aly', value: '16b'},
 { key: 'alx', value: '17a'}]

... though searching for the element with the given key (like 'give me the element which key is 'alz') is not as straight-forward as with simple object. That's why using it like you did - providing a separate array for ordering of the indexes - is another common approach. You can attach this array to that object, btw:

var arr={};
arr['alz']='15a';
arr['aly']='16b';
arr['alx']='17a';
arr['alw']='09c';
arr._keysOrder = ['alz', 'aly', 'alx', 'alw'];
like image 115
raina77ow Avatar answered Dec 11 '25 12:12

raina77ow


This is an object, not an array, and it sounds like you don't really want those strings to be keys.

How about a nice array?

var ar = [
  { key: 'alz', value: '15a' },
  { key: 'aly', value: '16b' },
  { key: 'alx', value: '17a' },
  { key: 'alw', value: '09c' }
];
like image 30
Lightness Races in Orbit Avatar answered Dec 11 '25 10:12

Lightness Races in Orbit