Rain120 / Web-Study

日常学习,工作写的笔记
66 stars 108 forks source link

实现n层嵌套数组的翻转 #21

Open Rain120 opened 2 years ago

Rain120 commented 2 years ago

实现n层嵌套数组的翻转

输入

[1, [2, [3, [4, null]]]]

输出

[4, [3, [2, [1, null]]]]

实现

function reverseArray(arr) {
    const a = arr.flat(Infinity).filter(Boolean).reverse();
    a.push(null);

    for (let i = a.length - 2; i >= 1; i--) {
        if (i === a.length - 2) {
            a[i] = [a[i], null];
            continue;
        }

        a[i] = [a[i], a[i + 1]]
    }

    return a.slice(0, 2);
}
function reverseArray(arr) {
    function reverse(arr, next) {
        if (arr[1] === null) {
            return [arr[0], next];
        }

        next = [arr[0], next ? next : null];

        return reverse(arr[1], next);
    }

    return reverse(arr, null);
}