In javascript, is开发者_运维百科 there an easy way to sort key-value pairs by the value (assume the value is numeric), and return the key? A jQuery way to do this would be useful as well.
(There are a lot of related questions about key-value pairs here, but I can't find one specifically about sorting.)
There's nothing easy to do this cross-browser. Assuming an array such as
var a = [
{key: "foo", value: 10},
{key: "bar", value: 1},
{key: "baz", value: 5}
];
... you can get an array of the key
properties sorted by value
as follows:
var sorted = a.slice(0).sort(function(a, b) {
return a.value - b.value;
});
var keys = [];
for (var i = 0, len = sorted.length; i < len; ++i) {
keys[i] = sorted[i].key;
}
// keys is ["bar", "baz", "foo"];
Let's assume we have an Array
of Objects
, like:
var data = [
{foo: 6},
{foo: 2},
{foo: 13},
{foo: 8}
];
We can call Array.prototype.sort()
help, use Array.prototype.map()
help to map a new array and Object.keys()
help to grab the key:
var keys = data.sort(function(a,b) {
return a.foo - b.foo;
}).map(function(elem, index, arr) {
return Object.keys(elem)[0];
});
Be aware of, Array.prototype.map()
requires Javascript 1.6 and Object.keys()
is ECMAscript5 (requires Javascript 1.8.5).
You'll find alternative code for all those methods on MDC.
As far as I know, there isn't a built-in Javascript function to sort an array by its keys.
However, it shouldn't take too much code to do it: just extract the keys into their own array, sort them using the normal sort
function, and rebuild the array in the right order. Something like this should do the trick:
function SortArrayByKeys(inputarray) {
var arraykeys=[];
for(var k in inputarray) {arraykeys.push(k);}
arraykeys.sort();
var outputarray=[];
for(var i=0; i<arraykeys.length; i++) {
outputarray[arraykeys[i]]=inputarray[arraykeys[i]];
}
return outputarray;
}
Now you can just call your function like so:
var myarray = {'eee':12, 'blah':34 'what'=>66, 'spoon':11, 'snarglies':22};
myarray = SortArrayByKeys(myarray);
And the output will be:
{'blah':34, 'eee':12, 'spoon':11, 'snarglies':22, 'what':66}
Hope that helps.
Working test page here: http://jsfiddle.net/6Ev3S/
Given
var object = {
'a': 5,
'b': 11,
'c': 1,
'd': 2,
'e': 6
}
You can sort object
's keys by their values using the following:
Object.keys(object).sort(function (a, b) {
return object[a] - object[b]
}))
Result
[ 'c', 'd', 'a', 'e', 'b' ]
If you can't count on the exended array and object properties,
you can use the original Array methods-
function keysbyValue(O){
var A= [];
for(var p in O){
if(O.hasOwnProperty(p)) A.push([p, O[p]]);
}
A.sort(function(a, b){
var a1= a[1], b1= b[1];
return a1-b1;
});
for(var i= 0, L= A.length; i<L; i++){
A[i]= A[i][0];
}
return A;
}
//test
var Obj={a: 20, b: 2, c: 100, d: 10, e: -10};
keysbyValue(Obj)
/* returned value: (Array)
e,b,d,a,c
*/
精彩评论