using javascript, trying convert json data format used in highcharts' basic line chart.
what have start with:
originalarray = [ ['valuea', 1], ['valuea', 0], ['valueb', 9], ['valueb', 9], ['valueb', 3], ['valuec', 11] ]
and i'm trying create using above:
desiredarray = [{ name: 'valuea', data: [1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0] }, { name: 'valueb', data: [0, 0, 0, 1, 0, 0, 0, 0, 0, 2, 0, 0] }, { name: 'valuec', data: [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1] }]
for additional context, 0-11 in originalarray[i][1]
references month (0 = january), , desiredarray
list of unique names , count of occurrences month.
so far, can:
- convert data new array of objects
- for each unique name in
originalarray
- create new object in
desiredarray
, , setname
attribute - add
data
attribute contains empty array
- create new object in
but run trouble, , can't figure out how to:
- loop through
originalarray
- if name in
originalarray
matches name indesiredarray
- increment counter in matching
seriesarray[i].data
array, using value oforiginalarray[i][1]
index (it 0-11).
- increment counter in matching
- if name in
so i'm asking:
- what's way iterate across
originalarray
, match unique values, , then act on matches pushdesiredarray
. - what's best way increment counters in
desiredarray[i].data
i'm open using libraries, such underscore.js. have been trying figure out couple of days now, pretty goes within bounds of javascript.
updated proper array initialization, now.
var max = originalarray.reduce(function(p,c){return math.max(p,c[1]);},0); var initsums = function(size) { var arr = new array(size); (var i=0;i<size;i++) arr[i]=0; return arr; } var map = originalarray.reduce(function(sums,val){ if (!sums.hasownproperty(val[0])) { sums[val[0]] = initsums(max+1); } sums[val[0]][val[1]]++; return sums; },{}); var desiredarray = object.keys(map).map(function(key) { return {name: key, data: map[key]}; });
what we're doing here multi-step process:
decide how big our arrays going need be, first scanning largest value in original array.
use object aggregate counts (using
array.reduce()
).transform object , properties array of name/data pair objects (using
array.map
).