![](/img/trans.png)
[英]Picking a random index from an array is always returning me the same index?
[英]Return always same color by index from javascript array
我有一個按鈕,可以用chartjs生成圖表餅圖。
基於插入的過濾器,我得到類似(Name | Value%)的結果:
Service_1 | 10
Service_2 | 15
Service_3 | 75
有時某些結果不會出現,例如:
Service_1 | 20
Service_3 | 20
Service_4 | 60
...
我想為每項服務使用始終相同的顏色。
例如
Service_1 always #ccc
Service_2 always #fff
Service_3 always #000
etc...
現在,我正在使用此有用的解決方案:使用http://google.github.io/palette.js/
//json_labels are for Name
//json_results are for Value%
var myChart = new Chart(ctx, {
type: 'pie',
data: {
labels: json_labels,
datasets: [{
label: '',
data: json_results,
backgroundColor: palette('rainbow', json_results.length).map(function(hex) {
return "#" + hex;
})
}],
...
但是地圖不能像我需要的那樣工作,因為如果Service_2沒有出現在結果中,則Service_3獲取#fff而不是#000,依此類推...
我想更正這一部分:
backgroundColor: palette('rainbow', json_results.length).map(function(hex) {
return "#" + hex;
})
我最多可以使用100個服務,因此可以創建固定100種顏色的數組。 但是我不知道映射正確的索引。
假設結果對象類似於{ service: 'Service_1', value: 10 }
嘗試這個:
palette('rainbow', 100) // <--- create a palette with every color
.reduce((c, n, i) => // then pick only colors that match a service name using the palette color index
[...c, ...(json_results.find(row => r.service == `Service_${i+1}`) ? [`#${n}`] : [])], [])
var palette = Array(100).fill().map((_, i) => `${i}`.padStart(6, '0')); json_results = [{ service: 'Service_12', value: 9 }, { service: 'Service_54', value: 10 }] var mapped = palette .reduce((c, n, i) => [...c, ...(json_results.find(r => r.service == `Service_${i+1}`) ? [`#${n}`] : [])], []) console.log(mapped)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.