Как посчитать количество предметов в массиве - PullRequest
0 голосов
/ 27 января 2020

Я хочу посчитать количество элементов в массиве, чтобы отобразить его на диаграмме, используя диаграмму. js

Это то, как я делаю это в настоящее время, но я не могу получить счетчик ит.

const dataArray = [];
let labelsArray = ['1 - Very Jialat', '2 - Jialat', '3 - Normal lor', '4 - Shiok a bit', '5 - Shiok ah '];
db.collection('Feedback Ratings').get().then((snapshot => {
  snapshot.docs.forEach(doc => {
    FeebackRatings = doc.data().response;

    let response = FeebackRatings.response;
    dataArray.push(FeebackRatings);

    // loop through the data array
    dataArray.forEach(response => {
      // -1 because if value is 1, i want to refer to index 0 of the array
      if (dataArray[response - 1]) {
        dataArray[response - 1] = dataArray[response - 1] += 1
      }
      if (!dataArray[response - 1]) {
        dataArray[response - 1] = 1
      }
    })
  })
}));

// expected outcome = [2, 1, 1] --- where first item in index represents the count of the item
console.log(dataArray);

let myChart = document.getElementById('myChart').getContext('2d');

let BarChart = new Chart(myChart, {
  type: 'pie', //can create diff types using this; bar, horizontal, pie, line, donut, radar
  data: {
    labels: labelsArray,
    datasets: [{
      label: 'Total number',
      data: dataArray,
      backgroundColor: 'pink'
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Feedback Statistics',
      fontSize: 25
    }
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.9.3/Chart.min.css" rel="stylesheet"/>
<canvas id="myChart"></canvas>

Ответы [ 2 ]

1 голос
/ 27 января 2020

Если это массив JS, просто используйте

dataArray.length
0 голосов
/ 27 января 2020

Вы пишете .then(), так что я думаю, вы можете иметь дело с обещанием. Если вы имеете дело с обещанием, код после обещания будет выполнен перед выполнением кода, представленного в .then (). Поэтому, возможно, потребуется это сделать.

1) Преобразовать код, который необходимо выполнить, в функцию

function displayChart(dataArray){
console.log(dataArray);

let myChart = document.getElementById('myChart').getContext('2d');

let BarChart = new Chart(myChart, {
  type: 'pie', //can create diff types using this; bar, horizontal, pie, line, donut, radar
  data: {
    labels: labelsArray,
    datasets: [{
      label: 'Total number',
      data: dataArray,
      backgroundColor: 'pink'
    }]
  },
  options: {
    title: {
      display: true,
      text: 'Feedback Statistics',
      fontSize: 25
        }
      }
    });

}

2) И вызвать эту функцию в конце метода then (). .

const dataArray = [0, 0, 0, 0, 0];
let labelsArray = ['1 - Very Jialat', '2 - Jialat', '3 - Normal lor', '4 - Shiok a bit', '5 - Shiok ah '];
db.collection('Feedback Ratings').get().then(snapshot => {
    snapshot.docs.forEach(doc => {
        FeebackRatings = doc.data().response;

        let response = FeebackRatings.response;


        // loop through the data array
        response.forEach(response, => {
            labelsArray.forEach((value, index) => {
                if (value == response) {
                    dataArray[index]++;
                }

            });

        })
    })
    displayChart(dataArray);
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...