Sam*_*son 16 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 }
}
Run Code Online (Sandbox Code Playgroud)
我想根据他们的cities.index属性按升序排序对象.所以我可以这样显示它们D3.js
.我确定在D3中有一种方法可以做到这一点,但在处理一系列对象时我还没想到它.
有帮助吗?
mdm*_*dml 29
您可以将匿名函数传递给Javascript Array.prototype.sort
以进行排序index
.D3有一个函数(v 3.x) ,可以很容易地升序排序:d3.ascending
cities.sort(function(x, y){
return d3.ascending(x.index, y.index);
})
Run Code Online (Sandbox Code Playgroud)
这是输出:
[
{"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}
]
Run Code Online (Sandbox Code Playgroud)
只要sort
你使用它之前D3,该阵列作为特拉维斯Ĵ在评论中提及。没有理由使用 D3 进行排序(d3.ascending
无论如何只是一个比较包装器)。
另外,请注意您在声明的末尾有一个}
您想要的地方]
。
您可以像这样访问每个对象的属性:
cities.sort(function(a, b){
return a["index"]-b["index"];
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
26279 次 |
最近记录: |