gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 01:22:01 24 4
gpt4 key购买 nike

我有一组用于 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com