1

I have an object like this:

object in JavaScript

I would like to do two things.

  1. Sort the properties based on their values
  2. I would to know the order (or index) for any given property. For example, after ordering, I would like to know that the index of 00D is the 5th.

How can I achieve this in JavaScript?

halfer
  • 19,824
  • 17
  • 99
  • 186
J86
  • 14,345
  • 47
  • 130
  • 228

1 Answers1

1

While you can not sort properties of an object, you could use an array of keys of the object, sort them and take the wanted element, you want.

var keys = Object.keys(object),     // get all keys
    indices = Object.create(null);  // hash table for indices

// sort by value of the object
keys.sort(function (a, b) { return object[a] - object[b]; });

// create hash table with indices
keys.forEach(function (k, i) { indices[k] = i; });

// access the 5th key
console.log(keys[5]);

// get index of 00G
console.log(indices['00G']);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thanks Nina, but I am after the index number. I want to supply `00G` and get its Index. Also I believe you're sorting the `keys` there, not the `values` which is what I'm after. – J86 Jun 08 '16 at 11:02