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!

4
  • what is half in this case? Commented May 30, 2017 at 11:08
  • See stackoverflow.com/questions/2450954/…. Commented May 30, 2017 at 11:09
  • @NinaScholz Sorry for my English) In my first example the array.length = 9, and the "half" is Math.ceil(array.length/2) => 5 ... Commented May 30, 2017 at 11:13
  • What have you tried so far minimal reproducible example? Commented May 30, 2017 at 11:19

3 Answers 3

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)

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

1 Comment

Perfect solution.
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);

4 Comments

You probably want index>>1 not index/2 here. Your note is valid for python2, for example, but JS will give you a float.
I added a code snippet, index/2 gives floor(index/2), it is a number not a float
@AloïsdeLaComble And now Increase an array length by 1... result went wrong
You are right ! My mistake ! It works with Math.floor
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; }

Comments

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.