I have the following associative array in javascript...
opt_array["wta"] = 23;
opt_array["cdp"] = 54;
opt_array["cdm"] = 54;
opt_array["ppv"] = 44;
I need to sort by the value(descending) and then by the key(in a specific order). So for instance in the above I need to output 54,54,44,23 and have the keys in this order if there is a tie. wta, cdp, cdm,ppv.
So the returned array would be...
opt_array["cdp"] = 54;
opt_array["cdm"] = 54;
opt_array["ppv"] = 44;
opt_array["wta"] = 23;
thanks
-
2that is actually an object, not an arrayJustin Bicknell– Justin Bicknell2013年03月12日 16:13:18 +00:00Commented Mar 12, 2013 at 16:13
4 Answers 4
You're not using opt_array as an array, you're using it as an object.
The properties of an object are unordered in JavaScript, you can't put them in any particular order.
The only time order seems to appear is when you're using an array as an array and using array "indexes", which are numeric strings. (Yes, really. Though we tend to write them as numbers, they're actually property names, and property names are always strings.)
You can get all the property names from your opt_array as an array, then sort them, then loop through that to produce output. For instance:
var index;
var names = Object.keys(opt_array);
names.sort();
for (index = 0; index < names.length; ++index) {
console.log(names[index] + ": " + opt_array[names[index]]);
}
(That uses Object.keys, which is an ES5 feature not present on all browsers. You can shim it for earlier browsers.)
Or if you like, you can have an array of objects, and sort the array by a property on those objects:
opt_array = [
{key: "wta", value: 23},
{key: "cdp", value: 54},
{key: "cdm", value: 54},
{key: "ppv", value: 44}
];
opt_array.sort(function(a, b) {
var rv;
if (a.key < b.key) {
rv = -1;
}
else if (a.key > b.key) {
rv = 1;
}
else {
rv = 0;
}
return rv;
});
But that may not be useful for whatever you're using opt_array for.
Comments
There is no such thing as an associative array in JavaScript. What you have there is an Object.
An Object has no order. Regardless of the order you set the keys in, it will arrange them in the way it sees fit. Therefore, you can't sort them.
4 Comments
opt_array[0] and suchlike.You can get an array of sorted keys by using Object.keys
var sortedKeys = Object.keys(opt_array).sort();
for(var i = 0; i < sortedKeys.length; i++){
console.log("opt_array['" + sortedKeys[i] +"'] = "+ opt_array[sortedKeys[i]]+ ";");
}
outputs:
opt_array['cdm'] = 54;
opt_array['cdp'] = 54;
opt_array['ppv'] = 44;
opt_array['wta'] = 23;
Comments
Brian:
Javascript functions sometimes are not powerful enough for arrays handling.
I used this javascript library PHPJS:
Sorting with javascript: http://phpjs.org/functions/asort/
Good luck!!!