0

I have this nested array.

var arr = [
    [{ a }, { b }, { c }, { d }],
    [{ a }, { b }],
    [{ a }, { b }, { c }],
    [{ a }]
];

and I need it to be like this.

var arr = [
    [{ a }, { a }, { a }, { a }],
    [{ b }, { b }, { b }],
    [{ c }, { c }],
    [{ d }]
];

Here is where I've come so far (not very far):

(function() {
  var arr = [
    [{ a:"a" }, { b:"b" }, { c:"c" }, { d:"d" }],
    [{ a:"a" }, { b:"b" }],
    [{ a:"a" }, { b:"b" }, { c:"c" }],
    [{ a:"a" }]
  ];

  for (i = 0, j = 0; i < arr.length; i++) {
    var childArray2 = arr[i];
    console.log("i: " + i + ", j: " + j);
  }
})();

I've recked my brain and I'm stuck, thanks so much for help!

neonduplex
  • 11
  • 1
  • 3
  • Can we assume equal objects are ever on the same index of the nested arrays? Also, note that your initial structure is not valid! – Shidersz Jan 19 '19 at 14:55
  • Add a [mcve] **in the question itself** and not only a link to an external resource (which may be offline, blocked or not reachable for some other reason...) – Andreas Jan 19 '19 at 14:56
  • Yes, in the original array it is 0:a, 1:b, 2:c, 3:d in each of the four arrays. – neonduplex Jan 19 '19 at 14:58

2 Answers2

0

I'm not 100% sure about your structure because the one you showed is not valid, so I have modifyed it a little. However, here you have one approach using reduce(), this approach uses the assumption that: equal objects are on the same index of the nested arrays

var arr = [
    [{a: "a"}, {b: "b"}, {c: "c"}, {d: "d"}],
    [{a: "a"}, {b: "b"}],
    [{a: "a"}, {b: "b"}, {c: "c"}],
    [{a: "a"}]
];

let res = arr.reduce((res, curr) =>
{
    curr.forEach((v, i) => res[i] = res[i] ? [...res[i], v] : [v]);
    return res;
}, []);

console.log(res);

An alternative version, that only use for loops could be the next one:

var arr = [
    [{a: "a"}, {b: "b"}, {c: "c"}, {d: "d"}],
    [{a: "a"}, {b: "b"}],
    [{a: "a"}, {b: "b"}, {c: "c"}],
    [{a: "a"}]
];

var newArr  = [];

for (var i = 0; i < arr.length; i++)
{
    for (var j = 0; j < arr[i].length; j++)
    {
        if (!newArr[j])
        {
            newArr[j] = [];
            newArr[j].push(arr[i][j]);
        }
        else
        {
            newArr[j].push(arr[i][j]);
        }
    }
}

console.log(newArr);
Shidersz
  • 16,846
  • 2
  • 23
  • 48
-1

How about this?

let a,b,c,d;
var arr = [
 [{ a }, { b }, { c }, { d }],
 [{ a }, { b }],
 [{ a }, { b }, { c }],
 [{ a }]
];

let pivotArr = arr => arr[0].map((x,i) => arr.map(x => x[i]));
pivotArr(arr);
Jon Wilson
  • 726
  • 1
  • 8
  • 23