0

I have a array like this:

var test = [
             [1,1,1],
             [0,1,1],
             [0,0,0],
             [0,0,0]
           ];

I'm wondering how to it from the bottom like this:

var test = [
             [0,0,0,1],
             [0,0,1,1],
             [0,0,1,1]
           ];

I've tried this example

var ReverseArray = [];
var length = test.length;
for(var i = length-1;i>=0;i--){
   ReverseArray.push(test[i]);
}

But I got this:

[
  [0,0,0],
  [0,0,0],
  [0,1,1],
  [1,1,1]
];

It's not what I'm looking for. Anybody have good suggestions? Thx :)

3
  • 1
    That's not JSON, it's an array of arrays. Anyway, have you tried using a nested loop? Commented Jun 27, 2017 at 3:10
  • Oops sorry, fix it right now, thanks! Commented Jun 27, 2017 at 3:11
  • Hi, I updated my question, thanks a lot!! :) Commented Jun 27, 2017 at 3:16

2 Answers 2

3

The code you've shown actually does reverse the input, but your desired output is a rotation, not a reversal.

Here's one way to do that with one line of code:

var test = [
             [1,1,1],
             [0,1,1],
             [0,0,0],
             [0,0,0]
           ];

var output = test[0].map((_,i) => test.map(a => a[i]).reverse());

console.log(output);

Or the same thing without arrow functions (in case you're using IE), formatted in a way that probably makes it a bit easier to follow:

var output = test[0].map(function(_,i) {
  return test.map(function(a) { return a[i] }).reverse();
});

That assumes that the outer array will have at least one entry and that all inner arrays are of the same length.

(Edit) Note that using plain loops would be more efficient, because you could loop backwards rather than having to call .reverse().

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

1 Comment

Wow it's a brilliant answer! Thanks so much I learned a lot! :)
1

Unfortunately, I don't think there are any nifty javascript tricks for rotating a matrix, but the below is still a pretty clean way to do it:

let cols = [], reversed = test.reverse();
for(let i = 0; i < reversed[0].length; i++)
    cols.push(reversed.map(row=> row[i]));

cols should be a matrix in the desired configuration. demo

1 Comment

Thanks a lot! The answer works perfectly, hope I can click the accept button twice!

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.