-2

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?

Keppy
  • 471
  • 1
  • 7
  • 23

2 Answers2

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • 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. – Keppy Feb 19 '19 at 12:24
1

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);
Salman A
  • 262,204
  • 82
  • 430
  • 521