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

2
  • 1
    You need to transpose the array to rearrange it in this way. Commented Mar 19, 2020 at 1:31
  • An what does that mean? Commented Mar 19, 2020 at 1:51

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

Comments

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]});

2 Comments

LOL! It's ok... i have a question: What does transpose mean? @StackSlave You rock! btw, thanks
Transfer to somewhere else.
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)

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.