javascript - Use .map to turn quantity into percentages -
i'd use javascript's lodash turn object of arrays percentages. here object:
gender = { female: [14, 33, 28, 49], male: [33, 50, 42, 61] }
i above object
genderpercent = { female: [0.2978, 0.3975, ..., ...], male: [0.7021, 0.6024, ..., ...] }
here tried:
_.map(gender, function (val, index, list) { gender["male"][gender["male"].length-1] / gender["male"][gender["male"].length-1] + gender["female"][gender["female"].length-1]) });
but doesn't seem work.
any suggestions? :)
(note: need solution scale time because gender array(s) continue grow each month.)
you can use loop if male , female lengths same:
var gender = { female: [14, 33, 28, 49], male: [33, 50, 42, 61] } var m = gender.male; var f = gender.female; var genderp = {female:[], male:[]}; (var = 0; < gender.female.length; i++) { var t = m[i] + f[i]; genderp.male.push(m[i]/t); genderp.female.push(f[i]/t); } console.log(json.stringify(genderp, null, 2)); /* { "female": [ 0.2978723404255319, 0.39759036144578314, 0.4, 0.44545454545454544 ], "male": [ 0.7021276595744681, 0.6024096385542169, 0.6, 0.5545454545454546 ] } */
_.zip
, _.unzip
can used:
var gender = { female: [14, 33, 28, 49], male: [33, 50, 42, 61] } var genderp = _.zipobject(['male', 'female'], _.chain(_.zip(gender.male, gender.female)) .map(function(pair) { var t = pair[0] + pair[1] return [pair[0] / t, pair[1] / t] }) .unzip() .value()); console.log(json.stringify(genderp, null, 2)); /* { "male": [ 0.7021276595744681, 0.6024096385542169, 0.6, 0.5545454545454546 ], "female": [ 0.2978723404255319, 0.39759036144578314, 0.4, 0.44545454545454544 ] } */
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/3.7.0/lodash.min.js"></script>
Comments
Post a Comment