2

I have an associative array named map:

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

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

I have tried solutions from similar questions like this one. However, I have not found one yet that preserves the values. They simply creates 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 also do not have a server so any solution must be JavaScript.

Community
  • 1
  • 1
Pat Myron
  • 4,437
  • 2
  • 20
  • 39
  • 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. – David W May 19 '15 at 23:38

2 Answers2

3

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.

Pointy
  • 405,095
  • 59
  • 585
  • 614
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?

Community
  • 1
  • 1
Jobst
  • 529
  • 3
  • 12
  • I actually do not have a server and the website is entirely front-end and hosted on github-pages. I should have mentioned that. – Pat Myron May 19 '15 at 23:54