1

I am trying to display two elements from my array one as the label ie "name of certain type of crop" and the other is the data itself i.e "quantity of the crop", my problem is that my chart if same crop appears more than ones it displayed separately with its quantity Here is the resulting image

on my app.js(express server)

 app.get('/crop', function (req, res) {
    return new Promise(function(resolve, reject){
    db.serialize(function(){
        db.all('SELECT * FROM harvests', function(err, rows){
            if (!err) {
                resolve(rows)
            }else{
                reject(err)
            }
        })
    })
    }).then(function(rows){
        res.json(rows);
    });
});

On the Html page

<canvas id="chart" ></canvas>

on the script

 $(document).ready(function(){
    $.ajax({
    url: 'http://localhost:3000/crop',
    type: 'get',
    dataType: 'json'
    }).then(function(rows){

    let labels = rows.map(function(e) {
    return e.keyCrop;
    });
    let data = rows.map(function(e) {
     return e.quantity;
    });

    let ctx = document.getElementById('chart').getContext('2d');
    let myChart = new Chart(ctx, {
    type: 'bar',
    data: {
    labels: labels,
    datasets: [{
    label: 'What Farmers are Growing',
    data: data,
    backgroundColor:
   'rgba(255, 99, 132, 0.2)',
    borderColor:
    'rgba(255, 99, 132, 1)',
    borderWidth: 1
        }]
    }
    });
    });
    })

I would expect a case where if the crop is same it adds their total quantity and display on one name (label)

1 Answer 1

1

you can make a function to add and remove the duplicates items before you are taking out the labels and datas separately from the rows array. It will add the duplicates values and make only one key pair in the object which you are getting from AJAX call.

const addDuplicate = () => {
  const rows = [
    { labels: 'Avocados', data: 100 },
    { labels: 'Maize', data: 25000 },
    { labels: 'Tomatoes', data: 50 },
    { labels: 'Tomatoes', data: 50 },
    { labels: 'Cabbages', data: 4000 },
    { labels: 'French Beans', data: 5500 },
    { labels: 'Avocados', data: 50000 },
    { labels: 'Avocados', data: 34000 },
    { labels: 'Tomatoes', data: 50 }
  ];

  for (let i = 0; i < rows.length; i++) {
    for (let j = i + 1; j < rows.length; j++) {
      if (rows[i].labels === rows[j].labels) {
        rows[i].data += rows[j].data;
        rows.splice(j, 1);
        j--;
      }
    }
  }
  console.log(rows);
};


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

Comments

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.