2

I am trying to unpack a csv for a data visualization with d3.js v5 and I am getting the following console error:

Uncaught TypeError: data.reduce is not a function

Here is the part of my code that is giving me an error:

sample();

function sample() {

const data = d3.csv('../static/sample.csv');

uncount = (data, accessor) =>
  data.reduce((arr, item) => {
    const count = accessor(item)
    for (let i = 0; i < count; i++) {
      arr.push({
        ...item
      })
    }
    return arr
  }, []);

const boxes = uncount(data, d => d.boxes);

const nest = d3
  .nest()
  .key(d => d.venue)
  .entries(boxes);

}

However, if I switch my data object like so (as opposed to the line reading in the csv), it works:

const data = [{
    "year": 2015,
    "tour": "The Red Bullet",
    "venue": "Rosemont theatre",
    "capacity": 4400,
    "boxes": 18
  },
  {
    "year": 2017,
    "tour": "Wings",
    "venue": "Allstate arena",
    "capacity": 18500,
    "boxes": 74
  },
  {
    "year": 2018,
    "tour": "Love Yourself",
    "venue": "United center",
    "capacity": 23500,
    "boxes": 94
  },
  {
    "year": 2019,
    "tour": "Love Yourself - Speak Yourself",
    "venue": "Soldier Field",
    "capacity": 61500,
    "boxes": 246
  }
];

Is this because D3 v5 uses the fetch api to return a promise?

altocumulus
  • 21,179
  • 13
  • 61
  • 84
bullybear17
  • 859
  • 2
  • 13
  • 31

1 Answers1

3

Is this because D3 v5 uses the fetch API to return a promise?

Yes. A promise does not have an reduce method. A simple solution would be to change sample to an async function, then await the value.

sample();

async function sample() {
  const data = await d3.csv('../static/sample.csv');

  uncount = (data, accessor) =>
    data.reduce((arr, item) => {
      const count = accessor(item)
      for (let i = 0; i < count; i++) {
        arr.push({
          ...item
        })
      }
      return arr
    }, []);

  const boxes = uncount(data, d => d.boxes);

  const nest = d3
    .nest()
    .key(d => d.venue)
    .entries(boxes);
}

Note that an async function always returns a promise.

3limin4t0r
  • 19,353
  • 2
  • 31
  • 52