这是我的数据。
var data = [
{"firstName":"John", "lastName":"Doe", "age":"24", "height":"5.2"},
{"firstName":"Sam", "lastName":"Sam", "age":"28", "height":"6.0"},
{"firstName":"Anna", "lastName":"Smith", "age":"25", "height":"5.8"},
{"firstName":"Willam", "lastName":"Will", "age":"22", "height":"5.2"},
{"firstName":"Peter", "lastName":"Jones", "age":"23", "height":"6.2"}
];
这就是我的尝试。
var sorted = data.sort(function(a, b){
return a.height - b.height;
});
console.log(data.sort(sorted));
答案 0 :(得分:0)
您可以使用
var data = [
{"firstName":"John", "lastName":"Doe", "age":"24", "height":"5.2"},
{"firstName":"Sam", "lastName":"Sam", "age":"28", "height":"6.0"},
{"firstName":"Anna", "lastName":"Smith", "age":"25", "height":"5.8"},
{"firstName":"Willam", "lastName":"Will", "age":"22", "height":"5.2"},
{"firstName":"Peter", "lastName":"Jones", "age":"23", "height":"6.2"}
];
data.sort(function(a,b){
return a.height - b.height;
});
console.log(data)
for (var i=0; i < data.length; i++) {
console.log(data[i]['height']);
}
请参阅此fiddle升序。
请参阅此fiddle降序。
答案 1 :(得分:0)
Try this...
var data = [{
"firstName": "John",
"lastName": "Doe",
"age": "24",
"height": "5.2"
}, {
"firstName": "Sam",
"lastName": "Sam",
"age": "28",
"height": "6.0"
}, {
"firstName": "Anna",
"lastName": "Smith",
"age": "25",
"height": "5.8"
}, {
"firstName": "Willam",
"lastName": "Will",
"age": "22",
"height": "5.2"
}, {
"firstName": "Peter",
"lastName": "Jones",
"age": "23",
"height": "6.2"
}];
function sortByKey(array, key) {
return array.sort(function(a, b) {
var x = a[key];
var y = b[key];
return ((x < y) ? -1 : ((x > y) ? 1 : 0));
});
}
data = sortByKey(data, 'height');
console.log(data);
for (var i = 0; i < data.length; i++) {
console.log(data[i]['height']);
}
&#13;