如何转置2x2阵列?

时间:2018-06-07 18:18:34

标签: javascript

我有一个表格中的数组:

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

我想将其转换为:

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

我需要以这种方式对其进行转换,以便将来自SQL的JSON格式数据放入一个似乎需要数组序列的高图图形中,如下所示 https://jsfiddle.net/gh/get/library/pure/highcharts/highcharts/tree/master/samples/highcharts/demo/streamgraph/

1 个答案:

答案 0 :(得分:4)

尝试这样的事情

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