Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Getting the max for an Api json data in react

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())

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading