1

I have this data:

var ArrdeArr = [[1,2,3],[5,6,3],[9,5,1]]
var letter  = [x,y,z]

And each array in the ArrdeArr belongs to the letter.

Expected Output:

[x,[1,5,9]];
[y,[2,6,5]];
[z,[3,3,1]];

If I don't make myself clear please let me know

Paul Rooney
  • 19,499
  • 9
  • 39
  • 60
Alonso
  • 13
  • 6

4 Answers4

2

You may try it like this:

var ArrdeArr = [[1,2,3],[5,6,3],[9,5,1]];
var letter  = ['x','y','z'];

const result = letter.map((e, i) => [e, ArrdeArr.map(_e => _e[i])]);

console.log(result);

The x, y, z doesn't exist in the context, so I replaced them with strings.

Hao Wu
  • 14,894
  • 4
  • 17
  • 48
0

You can use Array.prototype.reduce() combined with Array.prototype.map():

const arrDeArr = [[1,2,3], [5,6,3], [9,5,1]]
const letter  = ['x', 'y', 'z']
const result = arrDeArr.reduce((a, c, i, arr) => [...a, [letter[i], arr.map(a => a[i])]], [])

console.log(result)
Yosvel Quintero Arguelles
  • 17,270
  • 4
  • 37
  • 42
0

Assuming both the arrays are of same length

var ArrdeArr = [[1,2,3],[5,6,3],[9,5,1]]
  var letter = ["x", "y", "z"];
  var finalArray = []
  letter.map((letter, index) => {
    var nestedArr = [letter]
    ArrdeArr.map(element => {
      nestedArr.push(element[index])
    })
    finalArray.push(nestedArr)
  })

  console.log(finalArray)
Yatin Gaikwad
  • 1,010
  • 1
  • 11
  • 21
0

For some reason my brain wasn't working. Here's what I came up with:

function transpose(array){
  const r = array.map(()=>[]);
  array.forEach(a=>{
    a.forEach((n, i)=>{
      if(r[i])r[i].push(n);
    });
  });
  return r;
}
const trp = transpose([[1,2,3], [5,6,3], [9,5,1]]);
console.log(trp);
console.log({x:trp[0], y:trp[1], z:trp[2]});
StackSlave
  • 10,436
  • 2
  • 17
  • 33