I'm struggling with transforming a multidimensional array in JavaScript. Here is an example of the input array:
[
[['a',1],['b',2],['c',3]],
[['a',4],['d',2],['c',3],['x',5]],
[['a',1],['c',2],['f',3],['x',1],['o',7]]
]
The desired output should look like this:
[
["a",1,4,1],
["b",2,null,null],
["c",3,3,2],
["d",null,2,null],
["x",null,5,1],
["f",null,null,3],
["o",null,null,7]]
]
Basically, I need to merge parts of the array based on the first element and fill any gaps with "null".
For instance, the pair with "x" has values 5 and 1 in the second and third rows, so it should be ["x",null,5,1].
Every line represents charting data series after optimization, and maintaining the correct position of values is crucial.
Currently, I have managed to format the data as expected but I'm struggling to add the "null" values in the correct positions.
Below is my code:
var cubes = [
[['a',1],['b',2],['c',3]],
[['a',4],['d',2],['c',3],['x',5]],
[['a',1],['c',2],['f',3],['x',1],['o',7]]
];
var out = [];
for (var i=0; i<cubes.length; i++) {
for (var j=0; j<cubes[i].length; j++) {
out.push(cubes[i][j]);
for (var x=0; x<out.length-1; x++) {
if (out[x][0] == cubes[i][j][0]) {
out[x].push(cubes[i][j][1]);
out.pop();
}
}
}
}
console.log(out);
This code gives me the following output:
[
["a",1,4,1],
["b",2],
["c",3,3,2],
["d",2],
["x",5,1],
["f",3],
["o",7]
]
Moreover, I have a hunch that there might be a simpler way to achieve this, possibly using map/reduce functions, but my brain seems to be frozen today :/ Any suggestions?