2015-08-13 28 views
-1

這是我的數據。如何按高度對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)); 
+1

請,你需要閱讀此之前問:http://stackoverflow.com/help/how-to-ask這是一個貧窮的創作的問題 –

+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降序排列。

+0

Sahil gupta感謝速度回覆。我已經完成排序部分,我只想在控制檯中只取得排序的高度值。 – User123

+0

更新了答案! –

+0

嘿謝謝Sahil gupta你的代碼很簡單。你能告訴我它是如何工作的降序。 – User123

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']); 
 
}

http://jsfiddle.net/ejemhj50/

+0

真棒這是工作,你可以請解釋我是如何工作的。並讓我知道如何按降序排序。 – User123

+0

將此行更改爲降序返回((x> y)?-1:((x

+0

感謝您的回覆Deena。 – User123