javascript - JS data manipulation -
i have data this: (the real record has far more this)
year type quantity 2011 1000 2012 b 1000 2012 c 1000 2012 1000 2015 1000
json:
[{year:2011, type:a, quantity:1000},...]
and want have result this: (i want every year , every type has record there)
year type quantity 2011 1000 2011 b - 2011 c - 2012 1000 2012 b 1000 2012 c 1000 2015 1000 2015 b - 2015 c -
is there way this? underscore solution welcomed!
vanilla js, includes final sort
var yrs = [], types = [], tmp={}; data.foreach(function(item){ // create arrays of years , types if(yrs.indexof(item.yr) === -1){ yrs.push(item.yr); } if(types.indexof(item.type) === -1){ types.push(item.type); } // temp object used in next step holes tmp[item.yr + item.type] = true; }); yrs.foreach(function(yr){ types.foreach(function(type){ // fill in holes if(!tmp.hasownproperty(yr+type)){ data.push({yr: yr, type: type, qty: 0}); } }) }); data.sort(function(a,b){ return b.yr === a.yr ? a.type > b.type : +a.yr - +b.yr });
Comments
Post a Comment