0

I have a problem trying to use associative arrays/objects in node, I have the following code and I want to get the same order I use when i inserted elements.

var aa = []

aa[0] = 1
aa['second'] = 'pep'
aa['third'] = 'rob'
aa[4] = 2

for (var pos in aa)     console.log (aa[pos])

But internally node put/sort first the numbers.

Look real execution :

1
2
pep
rob

I have created a parallel dynamic structure to solve this problem, but I'd like to ask for another solution or idea to get this target.

Regards.

Ricardo.

  • Possible duplicate of [Does JavaScript Guarantee Object Property Order?](https://stackoverflow.com/questions/5525795/does-javascript-guarantee-object-property-order) – Sébastien Jan 02 '18 at 21:56

3 Answers3

2

First of all, I'd recommend to use dictionary but not array, for dynamic keys:

var aa = {};

Elements are listed as its default order. You could check its default order with:

var keys = Object.keys(aa);
for (var i = 0; i < keys.length; i++) {
    console.log(keys[i]);
}

If the default order is needed as the same order when inserting elements, try this to save the inserting order in another array:

var aa = {};
var keys = [];

aa[0] = 1
keys.push(0);

aa['second'] = 'pep'
keys.push('second');

aa['third'] = 'rob'
keys.push('third');

aa[4] = 2
keys.push(4);

for (var i = 0; i < keys.length; i++) {
    console.log(aa[keys[i]]);
}
T.Liu
  • 492
  • 1
  • 5
  • 16
2

You may also want to give some ES6 features a try. Given you want to store data in a hash-like data structure that preserves the order I would recommend to give Map a try:

var map = new Map();

map.set(0, 1);
map.set('second', 'pep');
map.set('third', 'rob');
map.set(4, 2);

for (var [key, value] of map) {
    console.log(key, value);
}

map.forEach(function (value, key) {
    console.log(key, value);
});
0

nodejs arrays are just objects with numbers as keys and some added functions to their prototype. Also assoc. arrays are usually two arrays with values hinged together via a common index. for example: let a = [1,2,3]; let b = ["one","two","three"]; also try to get away from looking through arrays with for loops. use the plethora of functions available to you via the prototype. for loops also iterate through enumerable properties on the objects prototype, so a for loop would incorrectly also iterate through that.

lluisrojass
  • 439
  • 1
  • 3
  • 12