需要在 angular 打字稿中格式化我的数组
Need to format my array in angular typescript
像下面这样获取我的数组
let myArr=[["529256","88163","50210","11843","19404","39807","25177"]]
下面我要格式化
let formatArr=[
["529256", undefined, undefined, undefined, undefined, undefined, undefined],
[undefined, "88163", undefined, undefined, undefined, undefined, undefined],
[undefined, undefined, "50210", undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, "11843", undefined, undefined, undefined],
[undefined, undefined, undefined, undefined, "19404", undefined, undefined],
[undefined, undefined, undefined, undefined, undefined, "39807", undefined],
[undefined, undefined, undefined, undefined, undefined, undefined, "25177"]
]
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
let myArr = [
["529256", "88163", "50210", "11843", "19404", "39807", "25177"]
]
let formatArray = myArr.flat(1).map((number, index, array) => {
const size = array.length;
return new Array(size).fill(undefined).map((item, innerIndex) => {
if (index === innerIndex) {
return number;
} else {
return undefined
}
});
})
console.log(formatArray)
你可以简单地使用 reduce 函数来实现这个
let myArr = [
["529256", "88163", "50210", "11843", "19404", "39807", "25177"]
]
const newArray = myArr[0].reduce((prev, next, index) => {
let arr = Array(myArr[0].length).fill(undefined)
arr[index] = next
return [...prev, arr]
},[])
console.log(newArray)
像下面这样获取我的数组
let myArr=[["529256","88163","50210","11843","19404","39807","25177"]]
下面我要格式化
let formatArr=[
["529256", undefined, undefined, undefined, undefined, undefined, undefined],
[undefined, "88163", undefined, undefined, undefined, undefined, undefined],
[undefined, undefined, "50210", undefined, undefined, undefined, undefined],
[undefined, undefined, undefined, "11843", undefined, undefined, undefined],
[undefined, undefined, undefined, undefined, "19404", undefined, undefined],
[undefined, undefined, undefined, undefined, undefined, "39807", undefined],
[undefined, undefined, undefined, undefined, undefined, undefined, "25177"]
]
The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.
let myArr = [
["529256", "88163", "50210", "11843", "19404", "39807", "25177"]
]
let formatArray = myArr.flat(1).map((number, index, array) => {
const size = array.length;
return new Array(size).fill(undefined).map((item, innerIndex) => {
if (index === innerIndex) {
return number;
} else {
return undefined
}
});
})
console.log(formatArray)
你可以简单地使用 reduce 函数来实现这个
let myArr = [
["529256", "88163", "50210", "11843", "19404", "39807", "25177"]
]
const newArray = myArr[0].reduce((prev, next, index) => {
let arr = Array(myArr[0].length).fill(undefined)
arr[index] = next
return [...prev, arr]
},[])
console.log(newArray)