简体   繁体   中英

How to sort an associative array by value and keep values?

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM