Trying to display table using data from chart

624 views Asked by At

I'm trying to render a table which has two columns based on what is selected (which bar is selected). Each bar is an array of dates.

So if the last bar is clicked, i want a table of months with how many times that month comes up in that array.

For instance, in the last bar, this is the array that shows up in the console created by the function in line 62:

0: {date: 5, count: 1}
1: {date: 7, count: 15}
2: {date: 7, count: 15}
3: {date: 7, count: 15}
4: {date: 7, count: 15}
5: {date: 7, count: 15}     

etc..

Function:

const table = (data, e ) =>{
    // get array of dates when bar is clicked 
    let newArr= data.datum.dimensions[0].datum.data.results.map((d) => d.Date)
    console.log(newArr)

    // convert into Date object 
    const datesArr = newArr.map(d => ({ date: new Date(d) , count : 0}))
    console.log(datesArr)


    // add month array with month as an integer and the the count of months (how many times each month shows up )
    const monthArr = datesArr.map((e) => ({date: e.date.getMonth(), count: 0}))
    monthArr.forEach((e) => e.count = datesArr.filter((d) => d.date.getMonth() === e.date).length)
    console.log(monthArr)
    setMonths(monthArr)
}

I'm using state and I simple want to render a table using JSX with this array and the count

So I want a table with the month in one column and the count in another - like this :

<tr>
      <th>Year
      <select name="format" id="format"
        onChange={(e) => {
             table()
        }}
      >
          <option value='months'>months</option>
  
      </select>
      </th>
      <th>
        count
      </th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>{months}</td>
      <td> // count goes here </td>
    </tr>
    
  </tbody>
</Table> */}

Here is the link to the full sandbox : https://codesandbox.io/s/nice-meitner-o70m1

1

There are 1 answers

1
Vinicius Katata On BEST ANSWER

Your logic is a little confusing in table(), I've just rewrote that to be must easy to understand it.

Besides that you just need a map over your months state, like this:

    <Table striped bordered hover size="sm">
      <thead>
        <tr>
          <th>
            Month
            <select name="format" id="format" onChange={console.log}>
              <option value="months">months</option>
              <option value="year">year</option>
            </select>
          </th>
          <th>count</th>
        </tr>
      </thead>
      <tbody>
        {months.map(({ date, count }, index) => (
          <tr key={index}>
            <td>{date}</td>
            <td>{count}</td>
          </tr>
        ))}
      </tbody>
    </Table>

Take a look at my changes to see if it was more clean, otherwise you have to filter your monthArr before map, because it has duplicate values.

https://codesandbox.io/s/summer-lake-g0wki?file=/src/chart.js