如何按高度对JavaScript数组进行排序,并在控制台中仅获取打印高度

时间:2015-08-13 06:26:49

标签: javascript

这是我的数据。

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));

2 个答案:

答案 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)

&#13;
&#13;
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;
&#13;
&#13;

http://jsfiddle.net/ejemhj50/