0

If I have an JavaScript array:

a = ["12", "34", "56", "78"];

and I want to make a new 2D array like this:

b = [ ["12345678"], ["34567812"], ["56781234"], ["78123456"] ];

I know this should be pretty simple but I just can't figure it out... My brain is kinda slow today... :/

0

2 Answers 2

5

Join the string at various pivot locations.

n = [];
for(i = 0; i < a.length; i++){
    n.push(a.slice(i).join("") + a.slice(0,i).join(""));
}

This outputs:

[ "12345678", "34567812", "56781234", "78123456" ]

I am not certain whether having nested single element arrays in the output was a mistake, but if that is required just add square brackets inside push.

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

Comments

1

You can use map in conjunction with concat like this:

var newA = a.map(function() {
    var copy = a.slice();
    return [copy.concat(copy.splice(0, arguments[1])).join('')];
});

// => [ ["12345678"], ["34567812"], ["56781234"], ["78123456"] ];

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.