0

I'm trying to get all unique values from a column of a dataset loaded from a csv file using d3.js.

Reading round I found solutions that look like this:

d3.csv("Data/FabSDO.csv", function(data) {
  return d3.map(data, function(d){return d.Distretto;}).keys() 
})

I don't get an array of unique values, but a "Promise" in which each row is the array of all data column names:

Promise {<pending>}
__proto__: Promise
[[PromiseStatus]]: "resolved"
[[PromiseValue]]: Array(500)
[0 … 99]
0: (14) ["", "Branca", "Dipartimento", "Distretto", "Gruppo erogatore", "Erogatore", "Matricola", "Regime", "DRG", "Mese", "Anno", "Volume", "Costo", "Valore"]

UPDATE:

I found a workaround, I don't know if it's the most efficient solution. The trick was to pass directly the column to a then() function. I make use of the datalib library to get the unique.

d3.csv("Data/FabSDO.csv", function(data) {
      return data.Distretto
    }).then(function(col) {
       return dl.unique(col)
    })

The problem is that I would like to keep the loading of the csv separated by the processing of the columns, but if I do:

 foo = d3.csv("Data/FabSDO.csv", function(data) {
          return data
        })
 foo.then(function(col) {
           return dl.unique(col.Distretto)
        })

I get "TypeError: Cannot read property 'length' of undefined". Col seems not to have a Distretto property anymore.

UPDATE2

I think I found a way to access the column values in a second call. This works ok. (I used jQuery each() to extract column values)

foo = d3.csv("Data/FabSDO.csv", function(data) {
    return data
})
var group = 'Distretto'

foo.then(function(col) {
    var vals = []
    $.each(col, function(i, j){vals.push(j[group])})

    vals = dl.unique(vals)

})
Bakaburg
  • 3,165
  • 4
  • 32
  • 64
  • last one from CDN https://cdn.jsdelivr.net/npm/d3@5.9.7/dist/d3.min.js – Bakaburg Jul 19 '19 at 14:40
  • @altocumulus In the question you propose as duplicate nothing is written about getting unique values... – Bakaburg Jul 19 '19 at 14:45
  • Unique values are not your main problem. If you use `d3.csv()` as proposed in that other question, the rest of your code will successfully extract unique values. – altocumulus Jul 19 '19 at 14:49
  • Notice, however, that you cannot just `return` a value from those callbacks: neither the old API (XMLHttpRequest) nor the new (Fetch) supports this due to them being asynchronous. Reference: [*How to return value from an asynchronous callback function?*](https://stackoverflow.com/questions/6847697/how-to-return-value-from-an-asynchronous-callback-function). – altocumulus Jul 19 '19 at 14:52
  • Even with the then() approach that code didn't work. I found a workaround anyway – Bakaburg Jul 19 '19 at 15:00
  • I'm not trying to do get the array out of the promise anymore. Just use a specific column of the dataset in a successive then() call. – Bakaburg Jul 19 '19 at 15:27

0 Answers0