【问题标题】:How to sort an array of google visualisation data如何对一组谷歌可视化数据进行排序
【发布时间】:2017-10-21 23:11:13
【问题描述】:

我将此数组传递给 google.visualization.arrayToDataTable 函数。 如何按第一列的月份字符串对这些数据进行排序?

[
 ["month", "Social", "Referral", "Direct", "All Visits"]
 ["Jan 2017", 102, 16, 3, 22,]
 ["May 2017",  13, 11, 22, 66]
 ["Apr 2017",  4, 13, 17, 59]
]

我尝试了几种方式对其进行排序,最终接近排序但数据混乱。 任何帮助表示赞赏。提前致谢。

PS:我正在使用 jquery/javascript 将谷歌图表作为任何容器中的小部件进行处理。

【问题讨论】:

  • 您使用哪种编程语言? (正确标记您的问题有助于吸引相关人员查看)
  • jscript 或 jquery

标签: javascript jquery arrays sorting


【解决方案1】:

假设 data 是您发布的数据被截断。

最简单的方法是:

data.sort(function (a,b){
    return new Date(a[0]).getTime() - new Date(b[0]).getTime()
)

但是,这是非常低效的,因为每次比较都必须一遍又一遍地解析日期。最好事先解析日期:

for(var i=0;i<data.length;i++){
    data[i].unshift(new Date(data[i][0]).getTime()) // add precomputed time at the start of each datapoint
}
data.sort(function (a,b){
    return a[0] - b[0]
)
for(var i=0;i<data.length;i++){
    data[i].shift() // remove the precomputed time, as it is no longer needed
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多