我有一组用于 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.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}
]
关于javascript - 根据 D3 中的属性值对对象进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25168086/