Reorder an array taking each nth element

I'm scratching my head on this one. I'm trying to write a function that takes an array arr and an integer n and outputs a new array made up of each n-th element (starting at index 0) of the original array, returning to the beginning if necessary when the end is reached.

For instance:

arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
n = 3
output = [0, 3, 6, 9, 1, 4, 7, 2, 5, 8]

Or :

arr = [0, 1, 2, 3, 4, 5, 6]
n = 2
output = [0, 2, 4, 6, 1, 3, 5]

Upvotes: 1

Views: 439

Answers (1)

Robert Messerle
Robert Messerle

Reputation: 3032

This should work:

function get_n_elements(arr, n) {
    if ( n === 1 ) return arr.slice();
    var i, j,
        len = arr.length,
        ret = [];
    for ( i = 0; i < n; i++ ) {
        for ( j = i; j < len; j += n ) {
            ret.push( arr[ j ] );
        }
    }
    return ret;
}

Upvotes: 4

Related Questions