1

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())
3
  • what is the value of PRICES variable? Commented Jan 4, 2022 at 0:23
  • @Dylan Its numbers Commented Jan 4, 2022 at 0:34
  • @Dylan yes exactly Commented Jan 4, 2022 at 0:39

2 Answers 2

1

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.