Reputation: 23
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
Upvotes: 1
Views: 86
Reputation: 19090
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)
Upvotes: 0
Reputation: 10617
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]});
Upvotes: 0
Reputation: 1200
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)
Upvotes: 0
Reputation: 20885
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.
Upvotes: 2