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

How to get percentage of a certain amount from array

So I made this Array and is trying to understand how I would get the percentage of e.g. a object that has a certain condition. This is my code:

 const Array = [{item:"pants", price:50},{item:"shirt", price:15},{item:"shoes", price:150},{item:"watch", price:2000}]

const myBudget = 300

const canBuyItemsPercent = (budget) =>{
    const totalItems = Array.length
     ??calculating percentage here??
}

>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

You can use a .filter method to filter out the items that are too expense for the given budget. That would return a (filtered) array. In order to get the percentage of items within the given budget, you would just divide the filter array length by the (total) array length and return that.

const canBuyItemsPercent = (budget) => {
  const totalItems = Array.length;
  const items = Array.filter((item) => budget >= item.price);
  return ` ${(items.length / totalItems) * 100}%`;
};
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