hsz
hsz

Reputation: 152206

Sort array by key in JavaScript

I've created an array in JavaScript and inserted objects with keys of object_ids:

var ar = [];

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Problem is when I print this out the array I get is:

[undefined, undefined, "b", undefined, "a", "d", undefined, undefined, "c"]

and

ar.length = 9

How do I prevent the array from auto filling with undefined values and simply save this array as a 4-element array?

Iteration over an array is not what I expect here.

Thanks!

Upvotes: 1

Views: 4450

Answers (6)

nobody
nobody

Reputation: 10645

There is no guarantee that iterating an Object using the for...in statement be in any specific order. The behavior is undefined in ECMA Script specification, quote:

The mechanics of enumerating the properties ... is implementation dependent.

Chrome doesn't iterate elements in order in many cases, last time I checked Opera went the same way and just now I read here that IE9 has adopted the same behavior. So your only solution that is guaranteed to keep both the association and order of elements is to use an Object to store keys and values and an Array to store the order:

var obj = { 4: 'a', 2: 'b', 8: 'c', 5: 'd' };
var order = [ 4, 2, 8, 5 ];

for( var i in order ) {
    //do something with obj[ order[i] ]
}

Upvotes: 0

rlemon
rlemon

Reputation: 17666

var arr = {
    0 : "hello",
    8 : "world",
    14: "!"
    };

var count = 0;
for (var k in arr) {
   ++count;
}

document.write(arr[0] + " " + arr[8] + arr[14] + " with a length of " + count );

Outputs hello world! with a length of 3

You can use an Object.. and here is how to collect the count (if you needed)

Fiddle

Upvotes: 0

maerics
maerics

Reputation: 156404

I think you are confusing the behavior of JavaScript Arrays with the associative-array behavior of all JavaScript objects. Try this instead:

var a = {};
a[4] = 'a';
a[2] = 'b';
a[8] = 'c';
a[5] = 'd';
a; // {'2':'b', '4':'a', '8':'c', '5':'d'}

Note that the key/value pairs in an object are not ordered in any way. To order the keys or values you must maintain your own array of ordering.

Upvotes: 1

Joe
Joe

Reputation: 82584

Here's what you are doing:

var ar = [];
ar[8] = 'c'; // creates [undefined, undefined, undefined, undefined, undefined, undefined, undefined, 'c'];

I believe this is what you want:

var ar = {};

ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';

Object.keys(ar).length == 4; // true

More information on Object.keys

Upvotes: 2

Dennis
Dennis

Reputation: 32598

You can use an object literal instead of an array

var ar = {};
ar[4] = 'a';
ar[2] = 'b';
ar[8] = 'c';
ar[5] = 'd';
// {"2":"b","4":"a","5":"d","8":"c"}

You can iterate like this:

for (var i in a) {
    console.log(a[i]);
}

Upvotes: 3

mkk
mkk

Reputation: 7693

what you want to do is probably:

array = {}
array["1"] = "b"
array["7"] = "aaa"

now array is:

 Object { 1="a", 7="b"}

is it right?

Upvotes: 0

Related Questions