Data manipulation cheatsheet in Javascript
 

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:
  1. Uses filter() to select only the items with status === MeterStatus.CONNECTED.
  1. It uses map() to extract just the country_code from each item.
  1. Creates a Set to remove duplicates automatically.
  1. Spreads the Set back into an array.
This approach is more efficient because:
  1. It avoids manual checking of duplicates with includes(), which can be slow for large arrays.
  1. It reduces the number of iterations over the data.
  1. 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) )];