0

I have a multidimensional array like below and I want to shift column positions using javascript or ES6 with no jquery or any other plugins.

Eg: Initial array will look like this.

1|2|3|4
2|2|6|4
4|2|3|4
9|2|7|4

How can I shift the 4th column to 1st position so that it will look like this?

4|1|2|3
4|2|2|6
4|4|2|3
4|9|2|7

Could someone can help with logic to shift any columns like this?

4
  • 1
    Please show us what have you tried? Commented Feb 19, 2019 at 11:33
  • 1
    Possible duplicate of Shifting rows and columns in 2D arrays - Javascript Commented Feb 19, 2019 at 11:38
  • @GeorgeJempty, no, my requirement is entirely different. Commented Feb 19, 2019 at 12:31
  • Then a) explain your requirement better and b) show us what you've tried Commented Feb 19, 2019 at 14:02

2 Answers 2

2

You can use array.map to re-arrange the values:

function rearrange(rows, pos) {
  return rows.map(function(cols) {
    return pos.map(function(i) {
      return cols[i];
    });
  });
}

var old_arr;
var new_arr;

old_arr = [
  [1, 2, 3, 4],
  [2, 2, 6, 4],
  [4, 2, 3, 4],
  [9, 2, 7, 4]
];
new_arr = rearrange(old_arr, [3, 0, 1, 2]);
console.log(new_arr);

old_arr = [
  [1, 2, 3, 4],
  [2, 2, 6, 4],
  [4, 2, 3, 4],
  [9, 2, 7, 4]
];
new_arr = rearrange(old_arr, [3, 2, 1, 0]);
console.log(new_arr);

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

2 Comments

this is for specific columns. How to make this as a function so that it will change for any column, like I can shift any columns such way.
See revised answer.
2

You could assing a mapped outer array with new items by slicing the inner arrays with a given index.

For getting the original sort, you could shiftby the delta of length and index.

const shift = (array, index) => array.map(a => [...a.slice(index), ...a.slice(0, index)]);


var array = [[1, 2, 3, 4], [2, 2, 6, 4], [4, 2, 3, 4], [9, 2, 7, 4]],
    index = 3;

array = shift(array, index);
console.log(array.map(a => a.join(' ')));

array = shift(array, array[0].length - index);
console.log(array.map(a => a.join(' ')));
.as-console-wrapper { max-height: 100% !important; top: 0; }

1 Comment

this is for a specific columns. How to make this as a function so that it will change back and forth, like I can shift any columns such way.

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.