2015-12-10 37 views
-2

我已經創建了一個數組。JSON對象數組。按最大值排序

樣本:

[ 
    { 
    title: "RandomTitle", 
    distance: 600 
    }, 
    { 
    title: "RandomTitle", 
    distance: 480 
    }, 
    { 
    title: "RandomTitle", 
    distance: 500 
    } 
] 

是否有可能得到數組中的對象基於最低距離值到最高進行排序?

我正在做一個循環,我在div中顯示內容,我希望它顯示用戶輸入的最近位置。

我的代碼的精簡版的版本: http://codepen.io/anon/pen/MKwqMv?editors=101

+0

https://stackoverflow.com/questions/979256/sorting-an-array-of-javascript-objects的可能重複 –

+0

有很多處理這個問題的SO答案,Array.sort文檔幾乎涵蓋了這個例子。 –

+0

arrgh。它是一個*對象*的數組,不是「JSON對象」(不管是什麼) – npup

回答

2

呀,只是定義一個適當的sort比較功能:

var obj = [{ 
 
    name: "RandomTitle", 
 
    distance: 600 
 
}, { 
 
    name: "RandomTitle", 
 
    distance: 480 
 
}, { 
 
    name: "RandomTitle", 
 
    distance: 500 
 
}]; 
 

 
obj.sort(function(a,b){return a.distance - b.distance}); // this is the key 
 

 
$(function() { 
 
    for (var i = 0; i < 3; i++) { 
 
    DOMresults = $("#unordered-list"); 
 
    name = obj[i].name; 
 
    distance = obj[i].distance; 
 
    console.log(obj) 
 

 
    resultsContent = '<li><p>Name: ' + name + '</p><p>Distance: ' + distance + '</p></li>'; 
 
DOMresults.append(resultsContent) 
 
    }; 
 

 
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<ul id="unordered-list"> 
 

 
</ul>

+0

這個工作很完美。謝謝!我會接受這個作爲時間限制的答案 – Christian4423

+1

沒問題,我很高興我可以幫忙。 :) – Shomz

0

是,使用sort功能。 假設你的陣列存儲在「ARR」 VAR你應該有類似

arr.sort(function(obj1, obj2) { 
    // obj1 and obj2 will be arr[0] and arr[1] at the first iteration, 
    // arr[1] and arr[2] on the second, etc 
    return ... // here you compare your objects, read the sort documentation provided in the link above. 
});