分享一个用于数组或者对象的排序的函数。该函数可以以任意深度的数组或者对象的值作为排序基数对数组或的元素进行排序。
代码如下:
显示可能和排序结果不一致,* 其键会被浏览器以字母顺序排序显示,但在for循环中则为正确的排序顺序
*/
function sort_object(object,subkey,desc)
{
var is_array = false;
if(Object.prototype.toString.call(object) === '[object Array]') {
is_array = true;
}
if(is_array) {
var keys = {length:object.length};
} else {
if(typeof(Object.keys) == 'function') {
var keys = Object.keys(object);
} else{
var keys = [];
for(var key in keys) {
keys.push(key);
}
}
}
for(var i=; i vali) {
var tmp = object[i];
object[i] = object[j];
object[j] = tmp;
}
} else {
if(valj < vali) {
var tmp = object[i];
object[i] = object[j];
object[j] = tmp;
}
}
} else {
//对象排序
var obi = object[ keys[i] ];
var obj = object[ keys[j] ];
if(Object.prototype.toString.call(subkey) === '[object Array]') {
var vali = obi;
var valj = obj;
for(var si=; si vali) {
var tmp = keys[i];
keys[i] = keys[j];
keys[j] = tmp;
}
} else {
if(valj < vali) {
var tmp = keys[i];
keys[i] = keys[j];
keys[j] = tmp;
}
}
}//is!array
}
}
if(is_array) {
return object;
} else {
var sorted = {};
for(var i=; i
用法如下:
用法1:
用法2:
cpu":,"cpuhz":,"cpuhz_use":,},{
"cpu":,}
];
//根据cpuhz_use字段进行排序
data = sort_object(data,'cpuhz_use');
console.log(data);
用法3:
用法4:
用法5:
用法6: