使用map()JavaScript将整列从列索引列表移动到多维数组的开头



我需要用n重新排序的多维数组,其中n最多可以是50个或更多

从这里开始,如果我列出列索引All,我可以重新排序,这也可能是50或更多

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

我只想列出我想重新排序的列的索引,并将这些列移动到数组的开头,使所有其他列按它们在中的顺序排列

Bob|Carol|Ted|Alice
a  |b    |c  |d
1  |2    |3  |4
A  |B    |C  |D 

如果索引列表为list=[3]所以我得到

Alice|Bob|Carol|Ted
d    |a  |b    |c
4    |1  |2    |3
D    |A  |B    |C

列表=[2,3]

Ted|Alice|Bob|Carol
c  |d    |a  |b
3  |4    |1  |2
C  |D    |A  |B

谢谢

这可能不是最有效的途径,但应该适用于您想要实现的目标。

  1. 复制原始标头
  2. 基于";toFront";阵列
  3. 映射到所有行:
    • 使用原始标题将每一行转换为一个对象
    • 映射到新的标头上,并从行对象返回关联的值

const data = [
[ 'Bob', 'Carol', 'Ted', 'Alice' ],
[ 'a', 'b', 'c', 'd' ],
[ 1, 2, 3, 4 ],
[ 'A', 'B', 'C', 'D']
];
const rearrange = (rows=[], toFront=[]) => {
const originalHeaders = [...rows[0]]
const remainingHeaders = [...rows[0]]
const frontHeaders = toFront.map(index => {
// set this one to null, to be filtered out later
remainingHeaders[index] = null
// grab the original header value
return originalHeaders[index]
})
// you don't want to modify the original headers directly,
// seeing as you might not end up with the desired result
// if you pass a `toFront` value like [1,2] or where
// any of the values come after another

const newHeaders = [
...frontHeaders,
...remainingHeaders.filter(v => v !== null)
]

return data.map(r => {
let row = {}
r.forEach((value, i) => {
row[originalHeaders[i]] = value
})
return newHeaders.map(h => row[h])
})
}
console.log(rearrange(data, [2,1]))

相关内容

最新更新