1

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.

3
  • Are you always going to have an array with exactly two sub-arrays? Commented Apr 19, 2019 at 19:21
  • will there be just a pair of arrays in the input? Commented Apr 19, 2019 at 19:21
  • 5
    "without looping" — anytime you have a list of things, something has to iterate ("loop") through the list items. There's no escaping it. Commented Apr 19, 2019 at 19:23

2 Answers 2

2

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

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

1 Comment

Very cool solution but, I afraid, to the detriment of readability
1

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.

1 Comment

return arr.map(b => b[index]); to generalize it to n arrays.

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.