javascript - 根据 D3 中的属性值对对象进行排序

标签 javascript arrays sorting d3.js

我有一组用于 D3 中的对象,例如

var cities = [
  { city: "London", country: "United Kingdom", index: 280 },
  { city: "Geneva", country: "Switzerland", index: 259 },
  { city: "New York City", country: "United States", index: 237 },
  { city: "Singapore", country: "Singapore", index: 228 },
  { city: "Paris", country: "France", index: 219 },
  { city: "San Francisco", country: "United States", index: 218 },
  { city: "Copenhagen", country: "Denmark", index: 217 },
  { city: "Sydney", country: "Australia", index: 215 },
  { city: "Hong Kong", country: "Hong Kong", index: 214 },
  { city: "Brisbane", country: "Australia", index: 208 }
}

我想根据 cities.index 属性对对象进行升序排序。这样我就可以在 D3.js 中显示它们。我确信在 D3 中有一种方法可以做到这一点,但在处理对象数组时我还没有弄清楚。

有什么帮助吗?

最佳答案

您可以将匿名函数传递给 Javascript Array.prototype.sortindex 排序。 D3 有一个函数 d3.ascending (v 3.x)这使得升序排序变得容易:

cities.sort(function(x, y){
   return d3.ascending(x.index, y.index);
})

这是输出:

[
 {"city":"Brisbane","country":"Australia","index":208},
 {"city":"Hong Kong","country":"Hong Kong","index":214},
 {"city":"Sydney","country":"Australia","index":215},
 {"city":"Copenhagen","country":"Denmark","index":217},
 {"city":"San Francisco","country":"United States","index":218},
 {"city":"Paris","country":"France","index":219},
 {"city":"Singapore","country":"Singapore","index":228},
 {"city":"New York City","country":"United States","index":237},
 {"city":"Geneva","country":"Switzerland","index":259},
 {"city":"London","country":"United Kingdom","index":280}
]

关于javascript - 根据 D3 中的属性值对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168086/

相关文章:

javascript - 您可以取消绑定(bind)到文档的 jQuery 函数吗?

c - 从函数返回指针作为静态变量

c# - 排序数据表列

regex - 如何按长度对一系列行进行排序?

如果 cookie 存在则自动执行 JavaScript

javascript - 类型错误 : Cannot read property 'push' of undefined - AngularJS

JQuery:对于每个唯一的数据属性(动态)获取值数组

c++ - 如何设计基于两个指标的排序算法?

javascript - 代理无法在扩展类中获取方法

javascript - Javascript中的反向数组而不改变原始数组