[Solved] Force order of array in JavaScript [duplicate]


You’ve created the array using indexes that are out of sequence, and then you access the array using indexes in sequence. Of course you’re going to see a different order.

There is no in-spec way to access those properties in the order you added them, if you add them with out-of-order indexes like that. You’ll have to keep track of that separately. E.g.:

var array = [];
var order = [];
order.push(1);
array[1] = 'test';
order.push(2);
array[2] = 'dddd';
order.push(3);
array[3] = 'aaaa';
order.push(4);
array[0] = 'good';

var i; // You didn't have this, but you want it

for (i = 0; i < order.length; ++i) {
    alert(array[order[i]]);
}

Of course, you’d probably combine the

order.push(x);
array[x] = y;

…into a function.

5

solved Force order of array in JavaScript [duplicate]