Home > Enterprise >  How to use params inside a group function
How to use params inside a group function

Time:10-01

I am working on a code that groups data and generates a JSON object with data for the treemap chart.

I have created the same code twice, with different data, that is the working code:

  // by category
  const treemap_by_category = portfolio_assets.reduce((acc,curr)=>{
  const {category, ticker, total_today_brl} = curr
  const existing = acc[category]||[]
  return {...acc, [category]:[...existing, { x: ticker, y: total_today_brl }]}
  },{})
  const treemap_categories = Object.entries(treemap_by_category).map(([name,data])=>({name, data})).filter( data => data.name !== "Dividas")
  console.log(treemap_categories)
  treemap_categories.sort((a,b)=>b.data.map(({y})=>y).reduce((a, e) => a   e, 0)-a.data.map(({y})=>y).reduce((a, e) => a   e, 0))

  // by broker
  const treemap_by_broker = portfolio_assets.reduce((acc,curr)=>{
    const {broker, ticker, total_today_brl} = curr
    const existing = acc[broker]||[]
    return {...acc, [broker]:[...existing, { x: ticker, y: total_today_brl }]}
  },{})
  const treemap_brokers = Object.entries(treemap_by_broker).map(([name,data])=>({name, data}))
  treemap_brokers.sort((a,b)=>b.data.map(({y})=>y).reduce((a, e) => a   e, 0)-a.data.map(({y})=>y).reduce((a, e) => a   e, 0))

Then I decided to use a function, to not repeat the code, with parameters, but I am getting an error. Module build failed - Parsing error. How could I fix that? That is the not working code:

  function treemap_by(group_type){
    const treemap_by_group_type = portfolio_assets.reduce((acc,curr)=>{
      const {`${group_type}`, ticker, total_today_brl} = curr
      const existing = acc[`${group_type}`] || []
      return {...acc, [`${group_type}`]:[...existing, { x: ticker, y: total_today_brl }]}
      },{})
      const treemap_group = Object.entries(treemap_by_group_type).map(([name,data])=>({name, data})).filter( data => data.name !== "Dividas")
      treemap_group.sort((a,b)=>b.data.map(({y})=>y).reduce((a, e) => a   e, 0)-a.data.map(({y})=>y).reduce((a, e) => a   e, 0))
      return treemap_group
  }

  const treemap_categories = treemap_by("category")
  const treemap_brokers = treemap_by("broker")

CodePudding user response:

I think ${group_type} is the issue here. Give below code a try

function treemap_by(group_type){
    const treemap_by_group_type = portfolio_assets.reduce((acc,curr)=>{
      const { ticker, total_today_brl} = curr
      const existing = acc[curr[group_type]] || []
      return {...acc, [curr[group_type]]:[...existing, { x: ticker, y: total_today_brl }]}
      },{})
      const treemap_group = Object.entries(treemap_by_group_type).map(([name,data])=>({name, data})).filter( data => data.name !== "Dividas")
      treemap_group.sort((a,b)=>b.data.map(({y})=>y).reduce((a, e) => a   e, 0)-a.data.map(({y})=>y).reduce((a, e) => a   e, 0))
      return treemap_group
  }
  • Related