2017-09-19 33 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))