C
C
colorkid2017-04-06 09:43:07
JavaScript
colorkid, 2017-04-06 09:43:07

How to glue a multidimensional array so that the values ​​from the subarrays go one by one?

Hello. Faced with a problem.
There is an array consisting of several subarrays equal in length to each other.
Example

var arr = [
  [1,2,3,4,5],
  [6,7,8,9,10]
];

You need to make a new array of this kind: I.e. you need to glue the subarrays into 1 array in such a way that the data elements of the subarrays go in turn one after another. How to solve it?
var arr2 = [1,6,2,7,3,8,4,9,5,10];

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton fon Faust, 2017-04-06
@colorkid

head-on solution

var arr2 = [];
for (var i=0; i< arr[0].length; i++) {
    for(var j=0; j<arr.length; j++) {
        arr2.push(arr[j][i]);
    }
}

S
Stepanya, 2017-04-06
@Stepanya

var array = Array.concat(arr1, arr2, ...);
to sort use
var sortedArray = array.sort();

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question