JSON对象的数组。按最大值排序

时间:2015-12-10 19:53:25

标签: javascript arrays json filter

我创建了一个数组。

样品:

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

是否可以根据最低距离值对数组中的对象进行排序?

我正在创建一个for循环,我在div中显示内容,我希望它显示最近的位置给用户输入。

我的代码的lite版本: http://codepen.io/anon/pen/MKwqMv?editors=101

2 个答案:

答案 0 :(得分: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>

答案 1 :(得分:0)

是的,使用sort功能。 假设您的数组存储在&#34; arr&#34; 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.
});