Skip to content

Instantly share code, notes, and snippets.

@fraserxu
Created March 20, 2015 04:53
Show Gist options
  • Save fraserxu/98a2a30601752526864f to your computer and use it in GitHub Desktop.
Save fraserxu/98a2a30601752526864f to your computer and use it in GitHub Desktop.
make a grouped array
var data = {"16":1,"17":5,"18":324,"19":396,"20":456,"21":441,"22":454,"23":525,"24":488,"25":499,"26":498,"27":551,"28":556,"29":556,"30":555,"31":558,"32":590,"33":543,"34":552,"35":621,"36":569,"37":593,"38":532,"39":565,"40":590,"41":625,"42":587,"43":624,"44":647,"45":718,"46":656,"47":724,"48":725,"49":690,"50":649,"51":650,"52":675,"53":666,"54":563,"55":663,"56":537,"57":619,"58":529,"59":535,"60":479,"61":484,"62":415,"63":457,"64":381,"65":332,"66":294,"67":333,"68":329,"69":262,"70":232,"71":245,"72":198,"73":198,"74":185,"75":193,"76":162,"77":221,"78":151,"79":155,"80":150,"81":122,"82":125,"83":99,"84":84,"85":115,"86":89,"87":105,"88":70,"89":65,"90":65,"91":59,"92":63,"93":55,"94":35,"95":38,"96":37,"97":27,"98":35,"99":30,"100":19,"101":19,"102":12,"103":12,"104":11,"105":8,"106":9,"107":5,"108":13,"109":5,"110":7,"111":2,"112":6,"113":3,"114":1};
var ages = [], years = [];
var groupIndex = 1;
var maxGroupIndex = 16;
// make years
for (var i = 18; i < 98; i++ ) {
years.push(i)
}
// split them by 5 years
while (groupIndex < maxGroupIndex) {
ages.push(years.splice(0, 5));
groupIndex ++;
}
// people older than 98
var olderGroup = [];
for (var i = 98; i < 120; i++ ) {
olderGroup.push(i)
}
// merge
ages.push(olderGroup);
function sum(arry) {
return arry.reduce(function(a, b) {
return a + b;
})
}
// assgin value
var group = {};
ages.forEach(function(age) {
var key = age[0] + '-' + age[age.length - 1];
group[key] = sum(age.map(function(_d) {
return data[_d] || 0;
}))
})
console.log(group)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment