2

I have an associative array:

     var map = new Array();
     map["exampleKey"] = 7;

The keys are strings and the values are integers. Some keys may have the same value.

I tried solutions from similar questions like this one. However, I have not found one yet that preserves the values. They simply create arrays with the keys in order. I need a sort that stores the keys and values in order (sorted by value) into some appropriate data structure.

I do not have a server so any solution must be JavaScript.

1
  • 2
    I think the solution you linked in your question describes rather well that pure associative arrays don't exist in JS; what it does have is only incidentally similar. What you want sounds like something you'll need to roll yourself. Commented May 19, 2015 at 23:38

2 Answers 2

4

There are no associative arrays in JavaScript (setting aside the Map class in ES2015). Object properties cannot be ordered; the runtime delivers property names by all APIs in an arbitrary order.

What you can do is grab the property names into an array via Object.keys() or some equivalent, and then sort that array and access the object properties in order by iterating through that array.

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

Comments

0

You can always post the array back to your own server (via ajax) and let PHP asort (or arsort) deal with it.

Alternatively read this:

How to sort an associative array by its values in Javascript?

1 Comment

I actually do not have a server and the website is entirely front-end and hosted on github-pages. I should have mentioned that.

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.