captDaylight
captDaylight

Reputation: 2234

Issue Reversing Array of Objects with JS

I'm parsing JSON and getting an array of objects with javascript. I've been doing this to then append an element for each object:

for(o in obj){ ... }

But I realized that for a certain situation I want to go backwards through the array. So I tried this before the for loop:

obj = obj.reverse();

However this isn't reversing the order of the objects in the array. I could simply put a count variable in the for loop to manually get the reverse, but I'm puzzled as to why reverse doesn't seem to work with object arrays.

Upvotes: 5

Views: 16686

Answers (2)

Pointy
Pointy

Reputation: 413846

There's no such thing as an "object array" in JavaScript. There are Objects, and there are Arrays (which, of course, are also Objects). Objects have properties and the properties are not ordered in any defined way.

In other words, if you've got:

var obj = { a: 1, b: 2, c: 3 };

there's no guarantee that a for ... in loop will visit the properties in the order "a", "b", "c".

Now, if you've got an array of objects like:

var arr = [ { a: 1 }, { b: 2 }, { c: 3 } ];

then that's an ordinary array, and you can reverse it. The .reverse() method mutates the array, so you don't re-assign it. If you do have an array of objects (or a real array of any sort of values), then you should not use for ... in to iterate through it. Use a numeric index.

edit — it's pointed out in a helpful comment that .reverse() does return a reference to the array, so reassigning won't hurt anything.

Upvotes: 13

Guffa
Guffa

Reputation: 700592

That's because the for (o in obj) doesn't iterate the array as an array, but as an object. It iterates the properties in the object, which also includes the members in the array, but they are iterated in order of name, not the order that you placed them in the array.

Besides, you are using the reverse method wrong. It reverses the array in place, so don't use the return value:

obj.reverse();

Upvotes: 2

Related Questions