基于D3中的属性值对对象进行排序

时间:2014-08-06 18:57:38

标签: 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中有一种方法可以做到这一点,但在处理一系列对象时我还没想到它。

任何帮助?

2 个答案:

答案 0 :(得分:27)

您可以将匿名函数传递给Javascript Array.prototype.sort,以便按index排序。 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}
]

答案 1 :(得分:4)

在您使用D3之前,只需sort数组,作为评论中提到的Travis J。没有理由使用D3进行排序(d3.ascending is just a comparison wrapper anyway)。

此外,请注意您在宣言结束时需要} {。}}


您可以这样访问每个对象的属性:

]