user3860911
user3860911

Reputation: 139

How to transpose an 2x2 array?

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/

Upvotes: 0

Views: 64

Answers (1)

mehulmpt
mehulmpt

Reputation: 16547

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))

Upvotes: 4

Related Questions