【问题标题】:Array of JSON objects. Sort by max value [duplicate]JSON 对象数组。按最大值排序[重复]
【发布时间】:2015-12-10 19:53:25
【问题描述】:

我已经创建了一个数组。

样本:

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

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

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

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

【问题讨论】:

  • 有多个 SO 答案可以解决这个问题,Array.sort 文档几乎完全涵盖了这个例子。
  • 啊。它是 objects 的数组,而不是“JSON 对象”(不管是什么)

标签: javascript arrays json filter


【解决方案1】:

是的,只要定义一个合适的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>

【讨论】:

  • 效果很好。谢谢!时间到了我会接受这个答案
  • 没问题,很高兴能帮上忙。 :)
【解决方案2】:

是的,使用sort 函数。 假设您的数组存储在“arr”变量中,您应该有类似

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

【讨论】:

    猜你喜欢
    • 2021-10-02
    • 2014-01-25
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 2023-03-11
    • 2023-01-19
    • 1970-01-01
    • 2017-10-04
    相关资源
    最近更新 更多