JGS
JGS

Reputation: 369

How to retrieve keys from nest() in d3.v3.min.js?

I am writing a code to find the top 6 activities based on the number of the ids. CSV is like: 10000 Electricity Bill Payment 10001 Water Bill Payment 10002 Gas Bill Payment 10003 Electricity Bill Payment 10001 Water Bill Payment 10001 Water Bill Payment

My code is :

d3.csv("activities.csv", function(error,data) {
//fetching and storing the activities as key and their individual count as value
countByActivties=  d3.nest()
       .key(function(d) { return d.ACTIVITY; })//.sortKeys(d3.ascending)
      .rollup(function(v) { return v.length; }).sortValues(d3.descending)
      //.sortValues(d3.ascending)
      //.sortValues(function(v, d){ return d3.ascending(d.length); })
      .entries(data);
    console.log(JSON.stringify(countByActivties));

The output is like:

[{"key":"Electricity Bill Payment","values":2},{"key":"Water Bill Payment","values":3},{"key":"Gas Bill Payment","values":1}]

For finding the top 6 activites based on their count(i.e sort by descending order on the count). I have tried the getKeys function, but is not working. Below is code snippet for the same:

 for(i=0;i<6;i++){
        countByActivties.getKeys(function(d){ return d.key;})
    } 

the error it is throwing is:

testchartfunction.html:56 Uncaught TypeError: countByActivties.getKeys is not a function.

What I am trying to do is to iterate along the key values to fetch the data.

Anyone any idea about the same?

Upvotes: 1

Views: 549

Answers (1)

Cyril Cherian
Cyril Cherian

Reputation: 32327

It appears you just want the top 6 elements in the array and then get its keys:

Instead of this

 for(i=0;i<6;i++){
        countByActivties.getKeys(function(d){ return d.key;});//there is no getKeys function in an array.
    } 

do this:

var keys = countByActivties
          .sort(function(a, b){return a.values-b.values})
          .slice(0,6)
          .map(function(d){ return d.key;})

First sort then get the to 6 elements.

Then extract the key from the 6 elements.

Upvotes: 2

Related Questions