Search code examples
arraysreactjssortingchart.jsreact-chartjs

Count the duplicates in a string array using React JS


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,
});

Solution

  • 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().