javascript - Refactor loop within loop to sum up total of property -




i have data:

const data = [{         date: '2017-08-4',         data: [{                     "name": "male",                     "value": 2,                   },                   {                     "name": "female",                     "value": 46,                   }                 ]     },     {         date: '2017-08-5',         data: [{                     "name": "male",                     "value": 2,                   },                   {                     "name": "female",                     "value": 20,                   }                 ] }] 

i want find total sum of value of male code.

let total_male_of_alldays = 0         data.foreach(obj => {             obj.data.foreach(obj2 => {                 if(obj2.name === 'male'){                     total_male_of_alldays += obj2.value                 }             })         }) 

the code working felt code isn't elegant enough. use native loop better performances i'm looking more readable. i'm open lodash method.

an alternate approach combination of array.prototype.reduce() , array.prototype.find().

data.reduce((result, entry) => {   result += entry.data.find(d => d.name === "male").value;   return result; }, 0); 

warning: yield correct result if there one male entry in data!

const data = [{    date: '2017-08-4',    data: [{      "name": "male",      "value": 2,    }, {      "name": "female",      "value": 46,    }]  }, {    date: '2017-08-5',    data: [{      "name": "male",      "value": 2,    }, {      "name": "female",      "value": 20,    }]  }];    const total_male_of_alldays = data.reduce((result, entry) => {  	result += entry.data.find(d => d.name === "male").value;    return result;  }, 0);    console.log(total_male_of_alldays);





wiki

Comments

Popular posts from this blog

Asterisk AGI Python Script to Dialplan does not work -

python - Read npy file directly from S3 StreamingBody -

kotlin - Out-projected type in generic interface prohibits the use of metod with generic parameter -