本文介绍了根据D3中的属性值对对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个用于D3的对象数组,例如
I have a array of objects for use in D3 e.g
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 }
}
我想根据对象的citys.index属性以升序对它们进行排序.这样我就可以在D3.js
中显示它们.我肯定在D3中有一种方法可以做到这一点,但是在处理对象数组时我还没有弄清楚.
I would like to order the objects in ascending order based on their cities.index property. So that I can display them as such in D3.js
. Im sure there is a way of doing this in D3 but I am yet to figure it out when dealing with an array of objects.
有帮助吗?
推荐答案
您可以将匿名函数传递给Javascript Array.prototype.sort
以按index
进行排序. D3具有功能 d3.ascending
(v 3.x)使其易于升序排列:
You can pass an anonymous function to the Javascript Array.prototype.sort
to sort by index
. D3 has a function d3.ascending
(v 3.x) that makes it easy to sort ascending:
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}
]
这篇关于根据D3中的属性值对对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!