Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 258
captDaylight Avatar asked Mar 14 '12 14:03

captDaylight


People also ask

How do you flip an array in JavaScript?

JavaScript Array reverse() The reverse() method reverses the order of the elements in an array. The reverse() method overwrites the original array.

What is the most efficient way to reverse a JavaScript array?

reverse() if you want in-place, or array. slice(). reverse() if you want a copy.

Does reverse function changes the original array in JavaScript?

To reverse an array without modifying the original, call the slice() method on the array to create a shallow copy and call the reverse() method on the copy, e.g. arr. slice(). reverse() . The reverse method will not modify the original array when used on the copy.


2 Answers

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.

like image 183
Pointy Avatar answered Oct 30 '22 13:10

Pointy


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();
like image 35
Guffa Avatar answered Oct 30 '22 15:10

Guffa