2015-12-10 36 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. 
});