2017-09-19 29 views
0

所以我使用Chart.js库来可视化一些数据。我已经将实例计算为类型并将它们存储在像这样的对象中。问题是我现在希望对这些价值进行排序,但没有参考的依据。排序没有数据参考点的相关阵列

Chart.js使用标签和数据以及单独的数组,因此这是我提出的解决方案。直到你希望对数据进行排序,它才能工作。第一个标签用于第一个数据等。

什么是更好的解决方案?

var apertures = { "labels": ["example", "exmple"], "data": [4, 18] } 

我想存储数据与标签,但我不知道如何使Chart.js做这样的魔术。

var chartAperture = new Chart(ctx, { 
    type: 'bar', 
    data: { 
     labels: apertures.labels, 
     datasets: [{ 
      label: 'Dataset 1', 
      backgroundColor: "rgba(255,225,0,0.5)", 
      borderColor: "#ffe100", 
      borderWidth: 1, 
      data: apertures.data 
     }] 
    } ... 

在此先感谢

+0

你的意思是,在排序前,第一个标签对应于第一数据? –

+0

@ThéophilePace我做 –

+0

你想如何对它们进行排序?通过增加订单,我假设? –

回答

1

嗯,我会做,在三个步骤。

步骤1:创建Array,具有标签/值的对象:

var step1 = apertures.labels.map(function (label, idx) { 
    return { label: label, value: apertures.data[idx] } 
}); 

步骤2:那种:

var step2 = step1.sort(function (i1, i2) { 
    //i1 - i2 or i2 - i1 determines acceding or descending order 
    return i1.value - i2.value; 
}); 

步骤3:恢复的对象:

var step3 = step2.reduce(function (result, item) { 
    result.labels.push(item.label); 
    result.data.push(item.value); 
    return result; 
}, { labels: [], data: [] }) 

你可以像这样链接:

var step3 = apertures.labels 
    .map(<function step 1>) 
    .sort(<function step 2>) 
    .reduce(<function step 3>); 
+0

我很兴奋使用地图,但然后'不能读属性'推'未定义在step2.reduce.lables' –

+0

它会这样工作,让我看看这个错误... – philipp

+0

固定,两个错别字... – philipp

0

我认为, 这将是更好的选择来写自己的功能,为chart.js之对数据进行排序。

你可以参考以下:

这里data.sort功能是用于排序的数据,

+0

http://jsfiddle.net/Lkdxxkfa/ –

+0

看起来不错,但功能是基于库的版本1,事情已经在图表对象中移动了一些。 –

0

您必须对表格数据进行排序并返回新的索引而不是值。然后,您只需将索引值推入新的光圈对象并返回即可。见下面的例子:

const apertures = { "labels": ["a", "b", "c", "d", "e"], "data": [4, 18, 0, 345, 1] } 
 

 
function sortByIncreasingOrder({ labels, data }) { 
 
    const newIndices = new Array(data.length) 
 
    for (let i = 0; i < newIndices.length; i++) 
 
     newIndices[i] = i 
 

 
    //I have no idea how you want to sort them. 
 
    // Because I'm not an artist, we're going to use < 
 
    //but you can use your own 
 
    myPersonnalOrder = (a, b) => (data[a] < data[b]) ? -1 : 1 
 

 
    
 
    newIndices.sort(myPersonnalOrder) 
 
    console.log("New indices : " + newIndices) 
 
    const sortedApertures = { "labels": [], "data": [] } 
 
    newIndices.forEach((value, index) => { 
 
     sortedApertures.labels[index] = apertures.labels[value] 
 
     sortedApertures.data[index] = apertures.data[value] 
 
    }) 
 
    return sortedApertures 
 
} 
 

 
console.log(sortByIncreasingOrder(apertures))