0

Following is a code I implemented to create a bar chart using chart js in React app. Here it creates a bar chart with all the data in an array. But, I want to change this code only to give the output in the x-axis - destination, y-axis - no. of occurrence of this destination since it has many repeated destinations. I searched methods to this but I couldn't get a correct solution. Can anyone help me to do this?

const dataArrayY4 = [];
res.data.map(item => {
  dataArrayY4.push(item.time)
})
const dataArrayX4 = []
res.data.map(item => {
  dataArrayX4.push(item.destination)
})
this.setState({
  data4: dataArrayY4,
  labels4: dataArrayX4,
});
2
  • Question. How would the dataArrayY4 represent the number of occurrence? Are you looking for occurrence on just one value or multiple values? Commented Apr 3, 2021 at 7:54
  • On one value. Like if the destination is Sri Lanka and it has occurred 5 times inside the array, then dataArrayY4 is 5 and dataArrayX4 is Sri Lanka Commented Apr 3, 2021 at 7:59

2 Answers 2

1

This could be done as follows:

const res = {
  data: [
    { time: 1, destination: 'A'},
    { time: 3, destination: 'A'},
    { time: 2, destination: 'B'}    
  ]
};

let tmp4 = [];
res.data.map((o, i) => {
  const existing = tmp4.find(e => e.destination == o.destination);
  if (existing) {
    existing.time += o.time;
  } else {
    tmp4.push({time: o.time, destination: o.destination});
  }
})

this.setState({
  data4: tmp.map(o => o.time);
  labels4: tmp.map(o => o.destination);
});

Above code could further be optimized by using Array.reduce() instead of Array.map().

Sign up to request clarification or add additional context in comments.

Comments

1

I would make the code more efficient. Instead of dataArrayY4 being an array, I would make it an object that has a key of value and the number of occurrence of each value. This way, you can count all the number of occurrences of the all items in res.data

const dataArrayY4 = {};
res.data.map(item => {
     dataArrayY4[item.destination] = (dataArrayY4[item.destination] || 0) + 1
 })
 
const dataArrayX4 = []
 res.data.forEach(item => {
    dataArrayX4.push(item.destination)
 })
this.setState({
    data4: dataArrayY4,
      labels4: dataArrayX4,
 });

Then if you want to look for the occurrence of a particular value you use this eg. Sri Lanka

this.state.data4['Sri Lanka']

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.