Skip to content Skip to sidebar Skip to footer

Force Order Of Array In JavaScript

I cannot seem to access my array via the order I provide, The array constantly reorders itself regardless of how I position its key and value within the array. An example of what I

Solution 1:

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.


Solution 2:

Just create the array in the order you want it to display. Notice the order of the indexes:

array[0] = 'test';
array[1] = 'dddd';
array[2] = 'aaaa';
array[3] = 'good';

Or by using push:

array.push('test');
array.push('dddd');
array.push('aaaa');
array.push('good');

Solution 3:

Do

var array = [];
array[0] = 'test';
array[1] = 'dddd';
array[2] = 'aaaa';
array[3] = 'good';

Post a Comment for "Force Order Of Array In JavaScript"