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?

3

1 Answer 1

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']);
Sign up to request clarification or add additional context in comments.

1 Comment

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.

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.