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 :
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}%`;
};