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
  • 20,879
  • 9
  • 40
  • 61
Alonso
  • 23
  • 1
  • 7

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
  • 17,573
  • 6
  • 28
  • 60
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
  • 18,669
  • 5
  • 37
  • 46
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,140
  • 1
  • 13
  • 23
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,613
  • 2
  • 18
  • 35