仅使用javascript或ES6在多维数组中移动整个列 [英] Shift entire column in multidimensional array using only javascript or ES6
本文介绍了仅使用javascript或ES6在多维数组中移动整个列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个像下面这样的多维数组,我想使用带有否 jquery或任何其他插件的javascript或ES6来移动列位置.
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
如何将第4列移至第1位,使其看起来像这样?
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?
推荐答案
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);
这篇关于仅使用javascript或ES6在多维数组中移动整个列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文