1

I have the only array:

[0, 1, 2, 3, 4, 5, 6, 7, 8]

The "first half" of array's data is [0,1,2,3,4] and the second is [5,6,7,8].

Now I should get something like this (it is not random mixing)

[0, 5, 1, 6, 2, 7, 3, 8, 4]

This is an array of data for two columns. I should place first half of data in first column, and the second one in second column.

I'm trying to find a simple solution... Thanks for advice!

Evan Trimboli
  • 29,900
  • 6
  • 45
  • 66
Andrew Koshkin
  • 446
  • 3
  • 16

3 Answers3

3

You can split your array in half using Math.ceil to round up number and then loop first part and add each element from second part incrementing counter by 2.

var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8], c = 1

var half = arr.splice(Math.ceil(arr.length / 2))
half.forEach(e => (arr.splice(c, 0, e), c += 2))

console.log(arr)
Nenad Vracar
  • 118,580
  • 15
  • 151
  • 176
1

Try the following, using map and an inline if statement

    var array = [0,1,2,3,4,5,6,7,8]
    var result = array.map(function(item,index){
      return (index%2 == 0) ? array[index/2] :  array[Math.floor((index+array.length)/2)];
    });
    console.log(result);
0

You could calculate the index and map the value from the array.

(i >> 1) + ((i & 1) * ((a.length + 1) >> 1))
^^^^^^^^                                     take the half integer value
            ^^^^^^                           check for odd
                          ^^^^^^^^^^^^       adjust length
                       ^^^^^^^^^^^^^^^^^^^^  the half value of adjusted length

var array = [0, 1, 2, 3, 4, 5, 6, 7, 8],
    result = array.map((_, i, a) => a[(i >> 1) + ((i & 1) * ((a.length + 1) >> 1))]);

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392