0

I have an array in the form:

var a1 = [
   ['AA', 1],
   ['AA', 2],
   ['AA', 3],
   ['BB', 7],
   ['BB', 8],
   ['BB', 9]
];

I want to transform it into:

output = [
           ['AA':1,2,3],
           ['BB':7,8,9] 
]

I need to transform it this way so I can put my JSON formatted data that comes from SQL into a highcharts graph that seems to need the array series as follows https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/streamgraph/

user3860911
  • 139
  • 1
  • 2
  • 7

1 Answers1

4

Try something like this

var a1 = [
   ['AA', 1],
   ['AA', 2],
   ['AA', 3],
   ['BB', 7],
   ['BB', 8],
   ['BB', 9]
];

function generateObj(array) {
  const obj = {}
  array.forEach(entry => {
    obj[entry[0]] = obj[entry[0]] || []
    obj[entry[0]].push(entry[1])
  })
  return obj
}

console.log(generateObj(a1))
mehulmpt
  • 15,861
  • 12
  • 48
  • 88
  • 1
    obj[entry[0]] = obj[entry[0]] || [] what does this line do? https://stackoverflow.com/questions/2538252/what-is-var-gaq-gaq-for oh it ensures it is defined so it doesn't fail - I see – user3860911 Jun 07 '18 at 18:38