1

I have the following array...

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

I need to convert it to the following...

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

Is this even possible?

1 Answer 1

4

Sure it's possible; something like this should work.

function manipulate(array, amount) {
    // The array to return
    var ret = [];

    // Add the first few values to the array
    // ret = [[1],[2],[3]];
    for (var i=0;i<amount;i++) {
        ret.push([array.shift()]);
    }

    // Now push the last few values on there.
    for (var i=0;array.length;i = ++i % amount) {
        ret[i].push(array.shift());
    }

    return ret;
}

and then call it like;

manipulate(arr, 3);
Sign up to request clarification or add additional context in comments.

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.