как отобразить 5 лучших значений в диаграмме google p ie - PullRequest

1 Ответ

0 голосов
/ 03 августа 2020

Моим решением было бы сохранить значения в массив, отсортировать массив, затем go по первым пяти.

Сортировка:

var a = [['Work', 8],['Eat', 2],['TV', 4],['Gym', 2],['Sleep', 8],['walk', 2],['games', 2],['chess', 2],['drink', 4],['dance', 6]];
a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] > b[1]) ? -1 : 1;
    }
}

для графика:

var data = google.visualization.arrayToDataTable([
    ['Task', 'Hours per Day'],a[0],a[1],a[2],a[3],a[4]
]);

все вместе:

var a = [['Work', 8], ['Eat', 2], ['TV', 4], ['Gym', 2], ['Sleep', 8], ['walk', 2], ['games', 2], ['chess', 2], ['drink', 4], ['dance', 6]];
a.sort(compareSecondColumn);

function compareSecondColumn(a, b) {
    if (a[1] === b[1]) {
        return 0;
    }
    else {
        return (a[1] > b[1]) ? -1 : 1;
    }
}



// Draw the chart and set the chart values
function drawChart() {
    var data = google.visualization.arrayToDataTable([
        ['Task', 'Hours per Day'],a[0],a[1],a[2],a[3],a[4]
        
    ]);
    // Optional; add a title and set the width and height of the chart
    var options = { 'title': 'the title', 'width': 550, 'height': 400 };
    // Display the chart inside the <div> element with id="piechart"
    var chart = new google.visualization.PieChart(document.getElementById('piechart'));
    chart.draw(data, options);
}

Подробнее о сортировке читайте в этом посте:

{ ссылка }

...