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

Javascript make calculations and filter list

I have below array –

const data=[
{
  month:"nov",
  veryLate:3,
  Late:5,
  onTime:2
},
{
  month:"dec",
  veryLate:1,
  Late:3,
  onTime:16
},
{
  month:"jan",
  veryLate:28,
  Late:1,
  onTime:1
},
}

I want to filter and make calculations on this array such that percentage can be obtained.

Eg. veryLate + Late+ onTime = (3+5+2) = 10

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

So percentage wise it is –

const data= [
{
  month:"nov",
  veryLate:30,
  Late:50,
  onTime:20
},
{
  month:"dec",
  veryLate:5,
  Late:15,
  onTime:80
},
,
{
  month:"jan",
  veryLate:98.33,
  Late:3.33,
  onTime:3.33
},]

To calculate this I had performed below , but getting syntax error over brackets –

var filteredData=data.map(x=>{
  x.month,
  x.veryLate/(x.veryLate+x.Late+x.onTime)*100,
  x.Late/(x.veryLate+x.Late+x.onTime)*100,
  x.onTime/(x.veryLate+x.Late+x.onTime)*100,
});

How can I obtained calculated results?

>Solution :

x.veryLate wont work in x it should be veryLate itself same for the others

const data=[
{
  month:"nov",
  veryLate:3,
  Late:5,
  onTime:2
},
{
  month:"dec",
  veryLate:1,
  Late:3,
  onTime:16
},
{
  month:"jan",
  veryLate:28,
  Late:1,
  onTime:1
},
]

var filteredData= data.map(x => (
   {
    ...x, 
    veryLate:  x.veryLate/(x.veryLate+x.Late+x.onTime)*100,         
    Late: x.Late/(x.veryLate+x.Late+x.onTime)*100, 
    onTime: x.onTime/(x.veryLate+x.Late+x.onTime)*100
  })
)

console.log(filteredData)

You also must wrap the returning object literal into parentheses. Currently the curly braces is being denoted as the function body.

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