Using Javascript, I am trying to convert some JSON data into the format used in Highcharts' basic line chart.
What I have to start with:
originalArray = [
['valueA', 1],
['valueA', 0],
['valueB', 9],
['valueB', 9],
['valueB', 3],
['valueC', 11]
]
And what I'm trying to create using the 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 some additional context, the 0-11 in originalArray[i][1]
references a month (0 = January), and the desiredArray
is a list of unique names and a count of their occurrences by month.
So far, I can:
- Convert the data into a new array of objects
- For each unique name in
originalArray
- Create a new object in the
desiredArray
, and set thename
attribute - Add a
data
attribute that contains an empty array
- Create a new object in the
But then I run into trouble, and can't figure out how to:
- Loop through the
originalArray
- If the name in the
originalArray
matches the name in thedesiredArray
- Increment a counter in the matching
seriesArray[i].data
array, using the value oforiginalArray[i][1]
as the index (it always be 0-11).
- Increment a counter in the matching
- If the name in the
So I'm asking:
- What's a good way to iterate across my
originalArray
, match up unique values, and then act only on those matches to push to thedesiredArray
. - What's the best way to increment the counters in
desiredArray[i].data
I'm open to using libraries, such as underscore.js. Have been trying to figure this out for a couple of days now, so pretty much anything goes within the bounds of Javascript.