2

How can I iterate over a javascript object, from back to front.

The object looks like this. {"33":140, "34":100, "35":120, "36":200}

I want it to display like this...

36 | 200
35 | 120
34 | 100
33 | 140

I tried sorting first then displaying, but it sorts by the second number, not the key. How would I either iterate from back to front, or reverse sort based on the key.

I realize this is pretty simple, but Im getting pretty frustrated with it....

5
  • 4
    There is no guarantee on the order when you iterate object properties. And you cannot sort objects. I believe you'll have to use an array of objects, and sort that. Commented Aug 23, 2013 at 21:36
  • @bfavaretto Correct, objects are not ordered -- but we sure can use the keys, sort them and use that (see my answer). Commented Aug 23, 2013 at 21:40
  • @IngoBürk I did, and upvoted your answer. That's indeed the best approach. Commented Aug 23, 2013 at 21:42
  • @bfavaretto Yeah, I didn't notice at first that both comments were you. D'oh. :) Commented Aug 23, 2013 at 21:43
  • One thing I learned today, objects are ordered, just not in the order they are defined. Commented Aug 23, 2013 at 22:07

1 Answer 1

5

A fairly modern version would look like this:

Object.keys(obj).sort(function (a, b) {
    return Number(b) - Number(a);
}).forEach(function (current) { 
    console.log(current + ' | ' + obj[current]); 
});

Similarly, but with a little bit more code, it could be written for older browsers, too. Or you use shims.

Sign up to request clarification or add additional context in comments.

5 Comments

This is really close to what the OP actually need (console.log(obj[current]))
He wanted to log both. I just thought I wouldn't take all the fun out of it. It solves the actual problem, he can deal with the output.
Thanks!!...very efficient, and compact.....much better than the solution I was busy cooking up...which relied on alternate arrays, and two loops, in a cumbersome function
@bfavaretto Since you already wrote the other part, I updated my answer. :)
The sort may fail if some of the numbers have 1 or 3 digits instead of 2. If that's the case, OP will need to pass a function and do an actual numeric comparison. Then the .reverse() could be eliminated as well.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.