Use of reduce
Sum of values:
data.reduce((sum, current) => (sum + current), 0);
also can be used to create a dictionary
data.reduce((plan, current) => (plan[current.name] = current.year), {});
can also be used to extract a single value:
const value = each.contracts.reduce<number | null>((cost, plan) => { if (plan.type === key) cost = parseFloat(plan.cost as string); return cost; }, null);
const planCost: IPlanCount = Object.values(PlanTypeEnum).reduce<IPlanCount>( (acc, key) => { acc[key] = each.contracts.reduce<number | null>((cost, plan) => { if (plan.type === key) cost = parseFloat(plan.cost as string); return 20; }, null); return acc; }, { [PlanTypeEnum.COMMODITY_VARIABLE]: null, [PlanTypeEnum.VARIABLE]: null, [PlanTypeEnum.FIXED]: null, [PlanTypeEnum.NON_COMMODITY_VARIABLE]: null, [PlanTypeEnum.BLACK_BOX_VARIABLE]: null, }, );
More optimized way of doing filtering sometimes (specific case)
using reduce and list:
const countryList = data.reduce<string[]>((country, datum) => { if (datum.status === MeterStatus.CONNECTED && !country.includes(datum.country_code)) country.push(datum.country_code); return country; }, []);
This optimized version:
- Uses
filter()
to select only the items withstatus === MeterStatus.CONNECTED
.
- It uses
map()
to extract just thecountry_code
from each item.
- Creates a
Set
to remove duplicates automatically.
- Spreads the Set back into an array.
This approach is more efficient because:
- It avoids manual checking of duplicates with
includes()
, which can be slow for large arrays.
- It reduces the number of iterations over the data.
- It leverages built-in JavaScript methods that are often optimized by the engine.
const countryList = [...new Set( data .filter(datum => datum.status === MeterStatus.CONNECTED) .map(datum => datum.country_code) )];