I have 5 variables: a
, b
, c
, d
and e
, and their values depend on the user input. Now I want to sort these variables depending on their values in descending order and then print them. For example, I have the following values:
a = 1, b = 1.5, c = 1, d = 3, e = 2
I wan开发者_如何转开发t to print a list like this:
d = 3
e = 2
b = 1.5
a = 1
c = 1
I have tried to achieve this using associative-array but I failed since it's not indexed. Could you please help me to solve this issue?
Well, something like
var vars = {a: 1, b: 1.5, c: 1, d: 3, e: 2}, keys = Object.keys(vars);
keys.sort(function (a, b) {
return vars[b] - vars[a];
});
keys.forEach(function (key) {
console.log(key + ' = ' + vars[key]);
});
seems to do the trick nicely. Note that this uses ES5 Object.keys, which isn't supported in some browsers, so if you want it to run in Opera and IE < 9, you'll have to do something like
if (typeof Object.keys !== 'function') {
Object.keys = function (obj) {
var keys = [], i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push(i);
}
}
return keys;
};
}
Oh, and it also uses ES5 forEach, so if you need to work with IE < 9, you'll have to do something like
if (typeof Array.prototype.forEach !== 'function') {
Array.prototype.forEach = function (func) {
for (var i = 0, l = this.length; i < l; i += 1) {
func(this[i], i);
}
};
}
Use: arr = [ [ "a", 1 ], [ "b", 1.5 ], ... ]
, and sort that array with custom sort function which uses only second item from each value.
精彩评论