Reputation: 175
I am trying to change an array which contains multiple arrays into a form that I can use for an external API.
Example:
[ [44.5,43.2,45.1] , [42, 41.2, 48.1] ]
into
[ [44.5,42], [43.2,41.2] , [45.1, 48.1] ]
Currently my code runs as this, but doesn't work
var newArr= [];
var tempArr= [];
for(var key in data){
tempArr.push(finalArr[key][key])
newArr.push(tempArr)
}
Is there some easier way to accomplish this without looping? I was thinking of maybe a map function but I'm not sure how to implement it here.
Upvotes: 1
Views: 793
Reputation: 98
var arr = [
[44.5, 43.2, 45.1],
[42, 41.2, 48.1]
];
var result = arr[0].map(function (el, index) {
return [el, arr[1][index]];
});
console.log(result);
But you have to be sure, that source arrays have same length.
Upvotes: 1
Reputation: 386848
You could transpose the arrays by reducing and mapping the values.
This works for any length.
const transpose = array => array.reduce((r, a) => a.map((v, i) => [...(r[i] || []), v]), []);
console.log(transpose([[44.5, 43.2, 45.1], [42, 41.2, 48.1]]));
.as-console-wrapper { max-height: 100% !important; top: 0; }
Upvotes: 2