hapless_cap
hapless_cap

Reputation: 217

controlling which data to sort in d3.js

Each object in my JSON array has two properties: name & age. I would like to sort my data in ascending order based on age. However, I don't know how to tell my code to sort my data based on age only. Below is the code I have been using. When I currently run the code, it seems to use the name property, which comes first.

var sortSquares = function() {
         svg.selectAll("rect")
            .sort(function(a, b) {
                return d3.ascending(a, b)
            })
            .transition()
            .....
            .....

Upvotes: 0

Views: 151

Answers (1)

mdml
mdml

Reputation: 22882

In order to sort by the attributes of your data, you need to tell d3.ascending specifically which attributes to look for. Try this:

.sort(function(a, b) {
    return d3.ascending(a.age, b.age)
})

Upvotes: 2

Related Questions