Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
39
rated 0 times [  43] [ 4]  / answers: 1 / hits: 38747  / 10 Years ago, wed, august 6, 2014, 12:00:00

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 }
}


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.



Any help?


More From » arrays

 Answers
6

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);
})


And here's the output:



[
{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}
]

[#69880] Tuesday, August 5, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
luna

Total Points: 698
Total Questions: 114
Total Answers: 93

Location: Israel
Member since Wed, Apr 14, 2021
3 Years ago
luna questions
;