如何根据数组深度分离数组元素

问题描述 投票:0回答:1

这是我要转换的原始数组:

const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];

这就是我想要的结果:

const result = [
    [1, 2, 4, 8, 9],
    [4, 5, 10, 11, 14, 15],
    [6, 7, 12, 13]
  ];

这种分离是基于阵列的深度

javascript
1个回答
-2
投票
//First time answering, but the first thing that comes to mind is 

const baseArray = [1, 2, 3, [4, 5, [6, 7]], 8, 9, [10, 11, [12, 13]], [14, 15]];

const someConditon = (numOrArray) => {
// add logic to determine if this will be flat or no
}
const result = baseArray .flatMap((numOrArray) => (someConditon(numOrArray) ? [numOrArray] : numOrArray));

console.log(result);
© www.soinside.com 2019 - 2024. All rights reserved.