如何解决将矩阵转换为按列的新平面数组 当前数组预期数组
我正在处理一个数组数组,每个内部数组都包含对象。
我想将此数组重新组织为平面数组,其中的顺序是按列排列的(见下文)。
目前我已经写了这个:
const newArray = [];
arr.map((rows,i) => {
rows.map((row) => {
newArray.splice(i,row);
});
});
但是订单在进一步的操作中开始出错。
(请注意,我在 Node 中使用了 Promise 库,因此将贴图视为法线贴图)
当前数组
const arr = [
[
{ Mapped_Index: 'Alignment',item_1: '-' },{ Mapped_Index: 'Alignment',item_2: '-',item_3: '-' },item_4: '-',item_5: '-' },item_6: '-',item_7: '-' }
],[
{ Mapped_Index: 'Autonomy',{ Mapped_Index: 'Autonomy',[
{ Mapped_Index: 'Belonging',{ Mapped_Index: 'Belonging',item_7: '-' }
]
]
预期数组
const arr = [
{ Mapped_Index: 'Alignment',item_7: '-' },item_7: '-' }
]
解决方法
看起来您想要转置原始矩阵,然后将其展平:
let result = arr[0].flatMap((_,i) => arr.map(row => row[i]));
,
第一步:将对象数组的数组合并为对象数组:
var merged = [].concat.apply([],arr);
第二步:按Mapped_Index
对对象进行排序
function compare( a,b ) {
if ( a.Mapped_Index < b.Mapped_Index ){
return -1;
}
if ( a.Mapped_Index > b.Mapped_Index ){
return 1;
}
return 0;
}
merged.sort(compare);
按字段名称排序作为第三步有点棘手。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。