我想从多维数组中提取
Columns
的子数组,并改变原始数组以删除 JavaScript 中的这些列
例如:如果我有一个数组
originalArray =
[
[A, B, C, D, E, F],
[a1,b1,c1,d1,e1,f1],
[a2,b2,c2,d2,e2,f2],
[a3,b3,c3,d3,e3,f3]
[
其中
A,B,C,D,E,F
是标题
我想按这个顺序提取列 [4,0,3]
subArray =
[
[E, A, D],
[e1,a1,d1],
[e2,a2,d2],
[e3,a3,d3]
[
originalArray =
[
[B, C, F],
[b1,c1,f1],
[b2,c2,f2],
[b3,c3,f3]
[
我发现了这个: 从多维数组中提取子数组并对原始数组进行变异
对行执行此操作
let subArray = originalArray.reduce((accumulator, current, index) => {
if (idxList.includes(index)) {
//if the current index is included in the idxList array,
//push the current value to the accumulator
accumulator.push(current);
} else {
//push the current value to the `tempArray`.
tempArray.push(current)
}
return accumulator;
}, []);
然后我将连接这两个数组
reorderedArray = [...subArray, ...originalArray]
Reduce 似乎是一种有趣的方法,看起来应该是一个简单的修复,但我不得不承认我很难理解
Reduce
预先感谢您的协助
您可以将缺失的索引添加到
order
并通过将嵌套数组与顺序索引映射来映射数组。
let
data = [['A', 'B', 'C', 'D', 'E', 'F'], ['a1', 'b1', 'c1', 'd1', 'e1', 'f1'], ['a2', 'b2', 'c2', 'd2', 'e2', 'f2'], ['a3', 'b3', 'c3', 'd3', 'e3', 'f3']],
order = [4, 0, 3],
seen = new Set(order),
i = 0;
while (order.length < data[0].length) {
while (seen.has(i)) ++i;
order.push(i++);
}
data = data.map(a => order.map(i => a[i]));
data.forEach(a => console.log(...a));
常规映射似乎可行:
function myFunction() {
var originalArray = SpreadsheetApp.getActive().getRange('Sheet1!A:F').getValues();
var subarray = originalArray.map(e=>[e[4],e[0],e[3]]);
originalArray = originalArray.map(e=>[e[1],e[2],e[5]]);
}
可能
function rearrangeCols(data, orderFront, orderBack) {
orderFront = orderFront.map( x => data[0].includes(x) ? data[0].indexOf(x) : null).filter(x => x != null);
orderBack = orderBack.map( x => data[0].includes(x) ? data[0].indexOf(x) : null).filter(x => x != null);
let
dataIdx = data[0].map( x => data[0].indexOf(x)),
remove = [...orderFront,...orderBack],
newOrder = [...orderFront,
... dataIdx.filter(item => !remove.includes(item)),
...orderBack
];
//Rearange data array
data = data.map(a => newOrder.map(i => a[i]));
return data;
}