How to fill array with for loop JavaScript Hello i have this code where i fill an array with for loop but its not correct i think its the for loop function, this is the code:
async function outlayGraph(label) {
const context = document.getElementById('outlayGraph').getContext('2d');
let data = 0;
let configuration = 0;
let allCurrency = [];
for (i in label) {
const item = label[i];
allCurrency.push(item.name);
}
data = {
labels: created_date,
datasets: [
{
label: allCurrency[i],
borderColor: generateRandomColor(),
data: albanianLek
},
]
};
console.log(data);
configuration = {
type: 'line',
data,
options: {
tooltips: {
mode: 'index'
}
}
};
if (charts) {
charts.data.labels = created_date;
charts.data.datasets[1].data = albanianLek;
charts.data.datasets[2].data = britishPound;
charts.data.datasets[3].data = americanDollar;
charts.data.datasets[4].data = euro;
charts.update();
console.log("update");
} else {
charts = new Chart(context, configuration);
console.log("create");
}
}
I only get the last value out of 5 values that the label has.
The issue is that you are only pushing the last value of the label array into the allCurrency array. You need to loop through the label array and push each item into the allCurrency array.
for (i in label) {
const item = label[i];
allCurrency.push(item.name);
}
You also need to update the datasets array in the data object to include all of the currencies in the allCurrency array.
data = {
labels: created_date,
datasets: allCurrency.map(currency => ({
label: currency,
borderColor: generateRandomColor(),
data: currency
}))
};
Please sign in or create an account to participate in this conversation.