I'm reading some data from an JSON and I am plotting the values vs time using Charts.js. However, I cannot manage to solve two things:
- I cannot read the last only 20 elements
- I cannot manage to make the bar change colors depending on the values
Regarding 1, I have managed to read the first 20 elements using return key<20;, but I don't know how to read the last elements. I have tried with return [key.length-1,key.length-20], but doesn't really work.
Regarding 2, I have tried different methods that some other people encountered and some codes from Fiddle, but it doesn't work. The console shows the elements in chartColors. Can anyone help me with these two issues?
The code below works just fine and give this:

And I would like something like this:

<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<canvas id="PM25">test</canvas>
</body>
<script type="text/javascript" src="https://canvasjs.com/assets/script/jquery-1.11.1.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.22.2/moment.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/chart.js@2.9.4"></script>
<script type="text/javascript">
var pm25 = document.getElementById('PM25').getContext('2d');
window.onload = function () {
var dataPoints1 = [];
$.getJSON("https://checkup-7b62e.firebaseio.com/meteo_radauti.json", function(meteo)
{
$.each(meteo, function(key, value){
dataPoints1.push({x: value[0], y: value[9]});
//How to make this array write the last 20 elements, and not the first 20, like it is now
return key<20;
});
var chartColors = {
red: 'rgb(255, 99, 132)',
blue: 'rgb(54, 162, 235)'
};
var PM25 = new Chart(pm25, {
type: 'bar',
data: {
labels: dataPoints1.map(x => x.x),
datasets:
[{
data: dataPoints1.map(y => y.y),
label: 'PM2.5 (ppm)',
backgroundColor: chartColors.blue,
borderColor: "red",
fill: true,
responsive: true
},
]}
});
var dataset = PM25.data.datasets[0];
for(i=0;i<dataset.data.length;i++){
var color="green";
if(dataset.data[i].value>40){
dataset.backgroundColor[i] = red;
}
else if(dataset.data[i].value>60){
dataset.backgroundColor[i] = blue;
}
console.log(dataset.backgroundColor[i])
}
PM25.update();
})}
</script>
</html>