Reputation: 29
I have fetched an Api data which is "PRICES" , and I'm trying to get the maximum for it but this function is not working , I would appreciate any help !
const pricedata = {
datasets: [
{
backgroundColor: '#0000',
barPercentage: 2,
barThickness: 5,
data: PRICES,
label: 'Update in prices',
maxBarThickness: 10
},
],
};
function findMax(PRICES) {
if (!PRICES) {
return;
}
return Math.max(...PRICES);
}
console.log(findMax())
Upvotes: 1
Views: 577
Reputation: 623
You forgot to put the PRICES variable in the function call on the last line
let PRICES = [1,2,3,4,5,6,7,8,9,10];
function findMax(PRICES) {
if (!PRICES) {
return;
}
return Math.max(...PRICES);
}
console.log(findMax(PRICES)) // outputs 10
OR remove that variable in the function
let PRICES = [1,2,3,4,5,6,7,8,9,10];
function findMax() {
if (!PRICES) {
return;
}
return Math.max(...PRICES);
}
console.log(findMax()) //outputs 10
Upvotes: 0
Reputation: 7717
I added the "price data" where you have PRICES in the data and added a 2nd chunk of data for illustration.
The code below loops over each "dataset" and, finds the max price and adds it as a new key called "maxPrice". Then it prints them out. This is just one way.
const pricedata = {
datasets: [
{
backgroundColor: "#0000",
barPercentage: 2,
barThickness: 5,
data: [1, 10, 30, 7, 42, 12],
label: "Update in prices",
maxBarThickness: 10
},
{
backgroundColor: "#0000",
barPercentage: 2,
barThickness: 5,
data: [11, 70, 18, 17, 24, 12],
label: "Update in prices",
maxBarThickness: 10
}
]
};
function findMax(PRICES) {
if (!PRICES) {
return 0;
}
return Math.max(...PRICES);
}
pricedata.datasets.forEach((dataset) => {
dataset.maxPrice = findMax(dataset.data);
});
pricedata.datasets.forEach((dataset) => {
console.log('max price is', dataset.maxPrice);
});
Update: Use a reducer to get the max of all the products...
const maxOfAllProducts = pricedata.datasets.reduce((accumulator, current) => Math.max(current.maxPrice, accumulator),0);
console.log('max of all products', maxOfAllProducts)
Upvotes: 1